GlobalExceptionHandler.java 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package com.jkcredit.invoice.config;
  2. import com.jkcredit.invoice.util.RespR;
  3. import lombok.extern.slf4j.Slf4j;
  4. import org.springframework.http.HttpStatus;
  5. import org.springframework.validation.BindException;
  6. import org.springframework.validation.FieldError;
  7. import org.springframework.web.bind.MethodArgumentNotValidException;
  8. import org.springframework.web.bind.annotation.ExceptionHandler;
  9. import org.springframework.web.bind.annotation.ResponseStatus;
  10. import org.springframework.web.bind.annotation.RestControllerAdvice;
  11. import java.util.List;
  12. /**
  13. * @description:
  14. * @author: sunzhaoning
  15. * @create: 2019-05-29 13:43
  16. * @version: V1.0
  17. **/
  18. @Slf4j
  19. @RestControllerAdvice
  20. public class GlobalExceptionHandler {
  21. /**
  22. * 全局异常
  23. *
  24. * @param e
  25. * @return RespR
  26. */
  27. @ExceptionHandler(Exception.class)
  28. @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
  29. public RespR exception(Exception e) {
  30. log.error("全局异常信息,异常信息为:{}", e.getMessage(), e);
  31. return new RespR<>(e);
  32. }
  33. /**
  34. * validation Exception
  35. *
  36. * @param exception
  37. * @return RespR
  38. */
  39. @ExceptionHandler({MethodArgumentNotValidException.class, BindException.class})
  40. @ResponseStatus(HttpStatus.OK)
  41. public RespR bodyValidExceptionHandler(MethodArgumentNotValidException exception) {
  42. List<FieldError> fieldErrors = exception.getBindingResult().getFieldErrors();
  43. RespR result = new RespR();
  44. result.setCode(1);
  45. result.setMsg(fieldErrors.get(0).getDefaultMessage());
  46. log.warn(fieldErrors.get(0).getDefaultMessage());
  47. return result;
  48. }
  49. }