SmartGlobalExceptionHandler.java 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package net.lab1024.smartadmin.handler;
  2. import java.util.List;
  3. import java.util.stream.Collectors;
  4. import org.springframework.beans.TypeMismatchException;
  5. import org.springframework.http.converter.HttpMessageNotReadableException;
  6. import org.springframework.validation.FieldError;
  7. import org.springframework.web.HttpRequestMethodNotSupportedException;
  8. import org.springframework.web.bind.MethodArgumentNotValidException;
  9. import org.springframework.web.bind.annotation.ControllerAdvice;
  10. import org.springframework.web.bind.annotation.ExceptionHandler;
  11. import org.springframework.web.bind.annotation.ResponseBody;
  12. import lombok.extern.slf4j.Slf4j;
  13. import net.lab1024.smartadmin.common.constant.ResponseCodeConst;
  14. import net.lab1024.smartadmin.common.domain.ResponseDTO;
  15. import net.lab1024.smartadmin.common.exception.SmartBusinessException;
  16. import net.lab1024.smartadmin.common.exception.SmartResponseCodeException;
  17. /**
  18. * [ 全局异常拦截 ]
  19. *
  20. * @author yandanyang
  21. * @version 1.0
  22. * @company 1024lab.net
  23. * @copyright (c) 2019 1024lab.netInc. All rights reserved.
  24. * @date
  25. * @since JDK1.8
  26. */
  27. @Slf4j
  28. @ControllerAdvice
  29. public class SmartGlobalExceptionHandler {
  30. /**
  31. * 添加全局异常处理流程
  32. *
  33. * @param e
  34. * @return
  35. * @throws Exception
  36. */
  37. @ResponseBody
  38. @ExceptionHandler(Exception.class)
  39. public ResponseDTO exceptionHandler(Exception e) {
  40. log.error("error:", e);
  41. // http 请求方式错误
  42. if (e instanceof HttpRequestMethodNotSupportedException) {
  43. return ResponseDTO.wrap(ResponseCodeConst.REQUEST_METHOD_ERROR);
  44. }
  45. // 参数类型错误
  46. if (e instanceof TypeMismatchException) {
  47. return ResponseDTO.wrap(ResponseCodeConst.ERROR_PARAM);
  48. }
  49. // json 格式错误
  50. if (e instanceof HttpMessageNotReadableException) {
  51. return ResponseDTO.wrap(ResponseCodeConst.JSON_FORMAT_ERROR);
  52. }
  53. // 参数校验未通过
  54. if (e instanceof MethodArgumentNotValidException) {
  55. List<FieldError> fieldErrors = ((MethodArgumentNotValidException) e).getBindingResult().getFieldErrors();
  56. List<String> msgList = fieldErrors.stream().map(FieldError :: getDefaultMessage).collect(Collectors.toList());
  57. return ResponseDTO.wrap(ResponseCodeConst.ERROR_PARAM, String.join(",", msgList));
  58. }
  59. if (e instanceof SmartBusinessException) {
  60. return ResponseDTO.wrap(ResponseCodeConst.SYSTEM_ERROR);
  61. }
  62. if (e instanceof SmartResponseCodeException) {
  63. return ResponseDTO.wrap(new ResponseCodeConst(((SmartResponseCodeException) e).getCode(), e.getMessage(),"0"));
  64. }
  65. return ResponseDTO.wrap(ResponseCodeConst.SYSTEM_ERROR);
  66. }
  67. }