CustomExceptionHandler.java 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package com.smart.reader.exception;
  2. import com.smart.reader.common.R;
  3. import com.smart.reader.enums.ExceptionResultCode;
  4. import org.springframework.validation.BindException;
  5. import org.springframework.validation.BindingResult;
  6. import org.springframework.validation.ObjectError;
  7. import org.springframework.web.bind.annotation.ExceptionHandler;
  8. import org.springframework.web.bind.annotation.RestControllerAdvice;
  9. import javax.validation.ConstraintViolationException;
  10. import java.util.List;
  11. import java.util.stream.Collectors;
  12. import javax.validation.ConstraintViolation;
  13. /**
  14. *
  15. *
  16. * @desc: 异常信息统⼀拦截
  17. */
  18. @RestControllerAdvice
  19. public class CustomExceptionHandler {
  20. /**
  21. * 参数校验异常
  22. *
  23. * @param ex
  24. * @return
  25. */
  26. @ExceptionHandler(value = BindException.class)
  27. public R errorHandler(BindException ex) {
  28. BindingResult result = ex.getBindingResult();
  29. StringBuilder errorMsg = new StringBuilder();
  30. for (ObjectError error : result.getAllErrors()) {
  31. errorMsg.append(error.getDefaultMessage()).append(", ");
  32. }
  33. errorMsg.delete(errorMsg.length() - 2, errorMsg.length());
  34. return R.fail(ExceptionResultCode.VALID_EXCEPTION.getCode(), errorMsg.toString());
  35. }
  36. /**
  37. * 参数校验异常
  38. *
  39. * @param ex
  40. * @return
  41. */
  42. @ExceptionHandler(ConstraintViolationException.class)
  43. public R validationErrorHandler(ConstraintViolationException ex) {
  44. List<String> errorInformation = ex.getConstraintViolations()
  45. .stream()
  46. .map(ConstraintViolation::getMessage)
  47. .collect(Collectors.toList());
  48. String message = errorInformation.toString().substring(1, errorInformation.toString().length() - 1);
  49. return R.fail(ExceptionResultCode.VALID_EXCEPTION.getCode(), message);
  50. }
  51. /**
  52. * ⾃定义异常
  53. *
  54. * @param customException
  55. * @return
  56. */
  57. @ExceptionHandler(value = CustomException.class)
  58. public R customExceptionHandler(CustomException customException) {
  59. String message = customException.getMessage();
  60. return R.fail(ExceptionResultCode.EXCEPTION.getCode(), message);
  61. }
  62. /**
  63. * 未知异常
  64. *
  65. * @param exception
  66. * @return
  67. */
  68. @ExceptionHandler(value = Exception.class)
  69. public R exceptionHandler(Exception exception) {
  70. exception.printStackTrace();
  71. return R.fail(ExceptionResultCode.EXCEPTION.getCode(), ExceptionResultCode.EXCEPTION.getMsg());
  72. }
  73. }