资讯专栏INFORMATION COLUMN

springboot 全局异常处理配置

刘福 / 2291人阅读

摘要:一使用实现全局异常处理注解定义全局异常处理类指定自定义错误处理方法拦截的异常类型同一个异常被小范围的异常类和大范围的异常处理器同时覆盖,会选择小范围的异常处理器定义异常业务类异常年月日定义自定义异常无数据系统异常年月日定义全局异常处理类异常

一、springboot Restful使用@ControllerAdvice、@ExceptionHandler、@ResponseBody实现全局异常处理
@ControllerAdvice 注解定义全局异常处理类
@ExceptionHandler 指定自定义错误处理方法拦截的异常类型
同一个异常被小范围的异常类和大范围的异常处理器同时覆盖,会选择小范围的异常处理器

1.定义异常业务类

</>复制代码

  1. /**
  2. * 异常VO
  3. *
  4. * @date 2017217
  5. * @since 1.0.0
  6. */
  7. public class ExceptionVO {
  8. private String errorCode;
  9. private String message;
  10. public String getMessage() {
  11. return message;
  12. }
  13. public void setMessage(String message) {
  14. this.message = message;
  15. }
  16. public String getErrorCode() {
  17. return errorCode;
  18. }
  19. public void setErrorCode(String errorCode) {
  20. this.errorCode = errorCode;
  21. }
  22. }

2.定义自定义异常

</>复制代码

  1. package exception;
  2. /**
  3. * 无数据Exception
  4. *
  5. * @date 17/4/25
  6. * @since 1.0.0
  7. */
  8. public class NotFoundException extends SystemException {
  9. public NotFoundException(String message) {
  10. super(message);
  11. }
  12. }
  13. /**
  14. * 系统异常
  15. *
  16. * @date 2017212
  17. * @since 1.0.0
  18. */
  19. public class SystemException extends RuntimeException {
  20. private static final long serialVersionUID = 1095242212086237834L;
  21. protected Object errorCode;
  22. protected Object[] args;
  23. public SystemException() {
  24. super();
  25. }
  26. public SystemException(String message, Throwable cause) {
  27. super(message, cause);
  28. }
  29. public SystemException(String message) {
  30. super(message);
  31. }
  32. public SystemException(String message, Object[] args, Throwable cause) {
  33. super(message, cause);
  34. this.args = args;
  35. }
  36. public SystemException(String message, Object[] args) {
  37. super(message);
  38. this.args = args;
  39. }
  40. public SystemException(Object errorCode, String message, Throwable cause) {
  41. super(message, cause);
  42. this.errorCode = errorCode;
  43. }
  44. public SystemException(Object errorCode, String message) {
  45. super(message);
  46. this.errorCode = errorCode;
  47. }
  48. public SystemException(Object errorCode, String message, Object[] args, Throwable cause) {
  49. super(message, cause);
  50. this.args = args;
  51. this.errorCode = errorCode;
  52. }
  53. public SystemException(Object errorCode, String message, Object[] args) {
  54. super(message);
  55. this.args = args;
  56. this.errorCode = errorCode;
  57. }
  58. public SystemException(Throwable cause) {
  59. super(cause);
  60. }
  61. public Object[] getArgs() {
  62. return args;
  63. }
  64. public Object getErrorCode() {
  65. return errorCode;
  66. }
  67. }

3.定义全局异常处理类

</>复制代码

  1. import java.util.HashMap;
  2. import java.util.Map;
  3. import java.util.stream.Collectors;
  4. import NotFoundException;
  5. import org.apache.commons.collections.CollectionUtils;
  6. import org.slf4j.Logger;
  7. import org.slf4j.LoggerFactory;
  8. import org.springframework.beans.factory.annotation.Autowired;
  9. import org.springframework.context.MessageSource;
  10. import org.springframework.context.NoSuchMessageException;
  11. import org.springframework.context.i18n.LocaleContextHolder;
  12. import org.springframework.http.HttpStatus;
  13. import org.springframework.validation.BindException;
  14. import org.springframework.validation.FieldError;
  15. import org.springframework.web.bind.annotation.ControllerAdvice;
  16. import org.springframework.web.bind.annotation.ExceptionHandler;
  17. import org.springframework.web.bind.annotation.ResponseBody;
  18. import org.springframework.web.bind.annotation.ResponseStatus;
  19. import ExceptionVO;
  20. /**
  21. * WEB异常处理器
  22. *
  23. * @date 2017216
  24. * @since 1.0.0
  25. */
  26. @ControllerAdvice("web") //指定异常处理期拦截范围
  27. public class WebExceptionHandler {
  28. static Logger LOG = LoggerFactory.getLogger(WebExceptionHandler.class);
  29. @Autowired
  30. private MessageSource messageSource;
  31. @ExceptionHandler(FieldException.class)
  32. @ResponseStatus(HttpStatus.CONFLICT) //指定http响应状态
  33. @ResponseBody
  34. /**
  35. * 未找到数据
  36. *
  37. * @param e
  38. * @return
  39. */
  40. @ExceptionHandler(NotFoundException.class)//指定异常类型
  41. @ResponseStatus(HttpStatus.NOT_FOUND)
  42. @ResponseBody
  43. public ExceptionVO handleNotFoundException(NotFoundException e) {
  44. ExceptionVO vo = new ExceptionVO();
  45. fillExceptionVO(e, vo);
  46. return vo;
  47. }
  48. @ExceptionHandler(SystemException.class)
  49. @ResponseStatus(HttpStatus.CONFLICT)
  50. @ResponseBody
  51. public ExceptionVO handleSystemException(SystemException e) {
  52. ExceptionVO vo = new ExceptionVO();
  53. fillExceptionVO(e, vo);
  54. return vo;
  55. }
  56. @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
  57. @ExceptionHandler(Exception.class)
  58. public void globalError(Exception e) {
  59. LOG.error(e.getMessage(), e);
  60. }
  61. /**
  62. * 填充异常响应消息
  63. *
  64. * @param e
  65. * @param vo
  66. */
  67. private void fillExceptionVO(SystemException e, ExceptionVO vo) {
  68. if (e.getMessage() != null) {
  69. String message = e.getMessage();
  70. try {
  71. message = messageSource.getMessage(e.getMessage(), e.getArgs(), LocaleContextHolder.getLocale());
  72. } catch (NoSuchMessageException ex) {
  73. ; // ignore
  74. }
  75. vo.setMessage(message);
  76. }
  77. vo.setErrorCode(String.valueOf(e.getErrorCode()));
  78. }
  79. }

二、springboot 返回 ModelAndView

</>复制代码

  1. package exception.handler;
  2. import javax.servlet.http.HttpServletRequest;
  3. import javax.servlet.http.HttpServletResponse;
  4. import org.springframework.web.servlet.HandlerExceptionResolver;
  5. import org.springframework.web.servlet.ModelAndView;
  6. @Commpent
  7. public class OverallExceptionHandler implements HandlerExceptionResolver {
  8. @Override
  9. public ModelAndView resolveException(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2,
  10. Exception ex) {
  11. ModelAndView mav = new ModelAndView();
  12. System.out.println(ex.getMessage());
  13. mav.addObject("errMsg", ex.getMessage());
  14. mav.setViewName("error");
  15. return mav;
  16. }
  17. }

其它方式:

</>复制代码

  1. @ControllerAdvice
  2. public class GlobalExceptionHandler {
  3. @ExceptionHandler(value = Exception.class)
  4. public ModelAndView resolveException(HttpServletRequest request, Exception ex) throws Exception {
  5. ModelAndView mav = new ModelAndView();
  6. System.out.println(ex.getMessage());
  7. mav.addObject("errMsg", ex.getMessage());
  8. mav.setViewName("error");
  9. return mav;
  10. }
  11. }

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/69000.html

相关文章

  • 基于SpringBoot的后台管理系统(Encache配置全局异常处理(重点))(四)

    摘要:因为抽象类天生就是用来被继承的。由于不支多继承,子类不能够继承多个类,但可以实现多个接口如果基本功能在不断改变,那么就需要使用抽象类。全局异常处理接下来,我们在看看控制统一的异常拦截机制。 3、Spring Boot 缓存配置、全局异常处理 说明 如果您有幸能看到,请认阅读以下内容; 1、本项目临摹自abel533的Guns,他的项目 fork 自 stylefeng 的 Guns!...

    Benedict Evans 评论0 收藏0
  • SpringBoot RESTful 应用中的异常处理小结

    摘要:和的区别方法注解作用于级别注解为一个定义一个异常处理器类注解作用于整个工程注解定义了一个全局的异常处理器需要注意的是的优先级比高即抛出的异常如果既可以让标注的方法处理又可以让标注的类中的方法处理则优先让标注的方法处理处理中的异常为了方便地展 @ControllerAdvice 和 @ExceptionHandler 的区别 ExceptionHandler, 方法注解, 作用于 Co...

    jackzou 评论0 收藏0
  • SpringBoot 实战 (十四) | 统一处理异常

    摘要:前言如题,今天介绍是如何统一处理全局异常的。主要是用于异常拦截出获取并将设置到消息类中返回。状态码异常拦截类通过加入来声明该类可拦截请求,同时在方法加入并在该注解中指定要拦截的异常类。测试访问测试正常返回数据结果。 微信公众号:一个优秀的废人如有问题或建议,请后台留言,我会尽力解决你的问题。 前言 如题,今天介绍 SpringBoot 是如何统一处理全局异常的。SpringBoot 中...

    arashicage 评论0 收藏0
  • springboot结合全局异常处理之登录注册验证

    摘要:在学校做一个校企合作项目,注册登录这一块需要对注册登录进行输入合法的服务器端验证,因为是前后端分离开发,所以要求返回数据。 在学校做一个校企合作项目,注册登录这一块需要对注册登录进行输入合法的服务器端验证,因为是前后端分离开发,所以要求返回JSON数据。方法有很多,这觉得用全局异常处理比较容易上手 全局异常处理 首先来创建一个sprIngboot的web项目或模块,目录结构如下 sho...

    leone 评论0 收藏0
  • SpringBoot:如何优雅地处理全局异常

    摘要:为了贴合主题,本次主要针对全局异常处理进行举例说明。自定义异常处理自定义一个异常自定义异常程序员小明错误码错误信息显而易见,这个异常继承了,属于运行时异常。包括处理其他异常,都是这种方式。 之前用springboot的时候,只知道捕获异常使用try{}catch,一个接口一个try{}catch,这也是大多数开发人员异常处理的常用方式,虽然屡试不爽,但会造成一个问题,就是一个Contr...

    李昌杰 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<