SpringMvc全局异常统一处理

港控/mmm° 2022-04-02 11:28 417阅读 0赞

全局异常处理还是基于AOP的思想,在SpringMvc中实现起来很简单,参照如下代码,其中的Resp是自定义的统一响应格式类,可自行设计,RespType是自定义的响应信息常量。

注意:该类所在的包必须被spring扫描到容器中。

  1. /**
  2. * 统一异常处理
  3. */
  4. @RestControllerAdvice
  5. public class ControllerExceptionHandler {
  6. private static final Logger logger = LoggerFactory.getLogger(ControllerExceptionHandler.class);
  7. /**
  8. * 400 - Bad Request 参数绑定出错
  9. */
  10. @ResponseStatus(HttpStatus.BAD_REQUEST)
  11. @ExceptionHandler(BindException.class)
  12. public Resp<String> handleBindException(BindException e) {
  13. logger.error("绑定参数出错", e);
  14. return new Resp<String>().error(RespType.BIND_PARAM_ERROR);
  15. }
  16. /**
  17. * 400 - Bad Request
  18. */
  19. @ResponseStatus(HttpStatus.BAD_REQUEST)
  20. @ExceptionHandler(HttpMessageNotReadableException.class)
  21. public Resp<String> handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
  22. logger.error("请求参数读取错误", e);
  23. return new Resp<String>().error(RespType.BAD_REQUEST);
  24. }
  25. /**
  26. * 400 - Bad Request
  27. */
  28. @ResponseStatus(HttpStatus.BAD_REQUEST)
  29. @ExceptionHandler({MethodArgumentNotValidException.class})
  30. public Resp<String> handleValidationException(MethodArgumentNotValidException e) {
  31. logger.error("请求参数验证失败", e);
  32. return new Resp<String>().error(RespType.BAD_REQUEST);
  33. }
  34. /**
  35. * 405 - Method Not Allowed。HttpRequestMethodNotSupportedException
  36. * 是ServletException的子类,需要Servlet API支持
  37. */
  38. @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
  39. @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
  40. public Resp<String> handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
  41. logger.error("请求方法不支持", e);
  42. return new Resp<String>().error(RespType.METHOD_NOT_ALLOWED);
  43. }
  44. /**
  45. * 415 - Unsupported Media Type。HttpMediaTypeNotSupportedException
  46. * 是ServletException的子类,需要Servlet API支持
  47. */
  48. @ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
  49. @ExceptionHandler({HttpMediaTypeNotSupportedException.class})
  50. public Resp<String> handleHttpMediaTypeNotSupportedException(Exception e) {
  51. logger.error("content-type类型不支持", e);
  52. return new Resp<String>().error(RespType.UNSUPPORTED_MEDIA_TYPE);
  53. }
  54. /**
  55. * 500 - Internal Server Error
  56. */
  57. @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
  58. @ExceptionHandler(Exception.class)
  59. public Resp<String> handleException(Exception e) {
  60. logger.error("服务器内部错误", e);
  61. return new Resp<String>().error(RespType.INTERNAL_SERVER_ERROR);
  62. }
  63. }

代码参照了 书呆子Rico 的文章 REST风格框架实战:从MVC到前后端分离(附完整Demo)

发表评论

表情:
评论列表 (有 0 条评论,417人围观)

还没有评论,来说两句吧...

相关阅读