|
| 1 | +package ru.javaops.bootjava.config; |
| 2 | + |
| 3 | +import jakarta.persistence.EntityNotFoundException; |
| 4 | +import jakarta.servlet.http.HttpServletRequest; |
| 5 | +import jakarta.validation.ValidationException; |
| 6 | +import lombok.AllArgsConstructor; |
| 7 | +import lombok.Getter; |
| 8 | +import lombok.extern.slf4j.Slf4j; |
| 9 | +import org.springframework.context.MessageSource; |
| 10 | +import org.springframework.context.i18n.LocaleContextHolder; |
| 11 | +import org.springframework.core.NestedExceptionUtils; |
| 12 | +import org.springframework.dao.DataIntegrityViolationException; |
| 13 | +import org.springframework.http.ProblemDetail; |
| 14 | +import org.springframework.lang.NonNull; |
| 15 | +import org.springframework.security.core.AuthenticationException; |
| 16 | +import org.springframework.security.web.firewall.RequestRejectedException; |
| 17 | +import org.springframework.validation.BindException; |
| 18 | +import org.springframework.validation.BindingResult; |
| 19 | +import org.springframework.validation.FieldError; |
| 20 | +import org.springframework.validation.ObjectError; |
| 21 | +import org.springframework.web.ErrorResponse; |
| 22 | +import org.springframework.web.HttpRequestMethodNotSupportedException; |
| 23 | +import org.springframework.web.bind.MissingServletRequestParameterException; |
| 24 | +import org.springframework.web.bind.annotation.ExceptionHandler; |
| 25 | +import org.springframework.web.bind.annotation.RestControllerAdvice; |
| 26 | +import org.springframework.web.servlet.NoHandlerFoundException; |
| 27 | +import ru.javaops.bootjava.error.*; |
| 28 | + |
| 29 | +import java.io.FileNotFoundException; |
| 30 | +import java.nio.file.AccessDeniedException; |
| 31 | +import java.util.LinkedHashMap; |
| 32 | +import java.util.Map; |
| 33 | +import java.util.Optional; |
| 34 | + |
| 35 | +import static ru.javaops.bootjava.error.ErrorType.*; |
| 36 | + |
| 37 | +@RestControllerAdvice |
| 38 | +@AllArgsConstructor |
| 39 | +@Slf4j |
| 40 | +public class RestExceptionHandler { |
| 41 | + public static final String ERR_PFX = "ERR# "; |
| 42 | + |
| 43 | + @Getter |
| 44 | + private final MessageSource messageSource; |
| 45 | + |
| 46 | + // https://stackoverflow.com/a/52254601/548473 |
| 47 | + static final Map<Class<? extends Throwable>, ErrorType> HTTP_STATUS_MAP = new LinkedHashMap<>() { |
| 48 | + { |
| 49 | +// more specific first |
| 50 | + put(NotFoundException.class, NOT_FOUND); |
| 51 | + put(FileNotFoundException.class, NOT_FOUND); |
| 52 | + put(NoHandlerFoundException.class, NOT_FOUND); |
| 53 | + put(DataConflictException.class, DATA_CONFLICT); |
| 54 | + put(IllegalRequestDataException.class, BAD_REQUEST); |
| 55 | + put(AppException.class, APP_ERROR); |
| 56 | + put(UnsupportedOperationException.class, APP_ERROR); |
| 57 | + put(EntityNotFoundException.class, DATA_CONFLICT); |
| 58 | + put(DataIntegrityViolationException.class, DATA_CONFLICT); |
| 59 | + put(IllegalArgumentException.class, BAD_DATA); |
| 60 | + put(BindException.class, BAD_REQUEST); |
| 61 | + put(ValidationException.class, BAD_REQUEST); |
| 62 | + put(HttpRequestMethodNotSupportedException.class, BAD_REQUEST); |
| 63 | + put(MissingServletRequestParameterException.class, BAD_REQUEST); |
| 64 | + put(RequestRejectedException.class, BAD_REQUEST); |
| 65 | + put(AccessDeniedException.class, FORBIDDEN); |
| 66 | + put(AuthenticationException.class, UNAUTHORIZED); |
| 67 | + } |
| 68 | + }; |
| 69 | + |
| 70 | + @ExceptionHandler(BindException.class) |
| 71 | + ProblemDetail bindException(BindException ex, HttpServletRequest request) { |
| 72 | + return processException(ex, request, Map.of("invalid_params", getErrorMap(ex.getBindingResult()))); |
| 73 | + } |
| 74 | + |
| 75 | + // https://howtodoinjava.com/spring-mvc/spring-problemdetail-errorresponse/#5-adding-problemdetail-to-custom-exceptions |
| 76 | + @ExceptionHandler(Exception.class) |
| 77 | + ProblemDetail exception(Exception ex, HttpServletRequest request) { |
| 78 | + return processException(ex, request, Map.of()); |
| 79 | + } |
| 80 | + |
| 81 | + ProblemDetail processException(@NonNull Exception ex, HttpServletRequest request, Map<String, Object> additionalParams) { |
| 82 | + String path = request.getRequestURI(); |
| 83 | + Class<? extends Exception> exClass = ex.getClass(); |
| 84 | + Optional<ErrorType> optType = HTTP_STATUS_MAP.entrySet().stream() |
| 85 | + .filter( |
| 86 | + entry -> entry.getKey().isAssignableFrom(exClass) |
| 87 | + ) |
| 88 | + .findAny().map(Map.Entry::getValue); |
| 89 | + if (optType.isPresent()) { |
| 90 | + log.error(ERR_PFX + "Exception {} at request {}", ex, path); |
| 91 | + return createProblemDetail(ex, optType.get(), ex.getMessage(), additionalParams); |
| 92 | + } else { |
| 93 | + Throwable root = getRootCause(ex); |
| 94 | + log.error(ERR_PFX + "Exception " + root + " at request " + path, root); |
| 95 | + return createProblemDetail(ex, APP_ERROR, "Exception " + root.getClass().getSimpleName(), additionalParams); |
| 96 | + } |
| 97 | + } |
| 98 | + |
| 99 | + private ProblemDetail createProblemDetail(Exception ex, ErrorType type, String defaultDetail, @NonNull Map<String, Object> additionalParams) { |
| 100 | + ErrorResponse.Builder builder = ErrorResponse.builder(ex, type.status, defaultDetail); |
| 101 | + ProblemDetail pd = builder.build().updateAndGetBody(messageSource, LocaleContextHolder.getLocale()); |
| 102 | + additionalParams.forEach(pd::setProperty); |
| 103 | + return pd; |
| 104 | + } |
| 105 | + |
| 106 | + private Map<String, String> getErrorMap(BindingResult result) { |
| 107 | + Map<String, String> invalidParams = new LinkedHashMap<>(); |
| 108 | + for (ObjectError error : result.getGlobalErrors()) { |
| 109 | + invalidParams.put(error.getObjectName(), getErrorMessage(error)); |
| 110 | + } |
| 111 | + for (FieldError error : result.getFieldErrors()) { |
| 112 | + invalidParams.put(error.getField(), getErrorMessage(error)); |
| 113 | + } |
| 114 | + log.warn("BindingException: {}", invalidParams); |
| 115 | + return invalidParams; |
| 116 | + } |
| 117 | + |
| 118 | + private String getErrorMessage(ObjectError error) { |
| 119 | + return messageSource.getMessage(error.getCode(), error.getArguments(), error.getDefaultMessage(), LocaleContextHolder.getLocale()); |
| 120 | + } |
| 121 | + |
| 122 | + // https://stackoverflow.com/a/65442410/548473 |
| 123 | + @NonNull |
| 124 | + private static Throwable getRootCause(@NonNull Throwable t) { |
| 125 | + Throwable rootCause = NestedExceptionUtils.getRootCause(t); |
| 126 | + return rootCause != null ? rootCause : t; |
| 127 | + } |
| 128 | +} |
0 commit comments