总结Spring异常处理

发布时间:2020-07-27 14:49:00 作者:小猪
来源:亿速云 阅读:132

这篇文章主要为大家展示了总结Spring异常处理,内容简而易懂,希望大家可以学习一下,学习完之后肯定会有收获的,下面让小编带大家一起来看看吧。

1. 前言

统一的异常处理对于应用的重要性不言而喻。今天我们来介绍一下 Spring 如何来进行统一的 Rest 异常处理。同时我们也会简单比较一下它们之间的优劣。

2. @Controller 结合 @ExceptionHandler

在控制器中声明一个方法然后用 @ExceptionHandler 注解标记即可:

 @Controller
 @RequestMapping("/test")
 public class TestController {
 
   @RequestMapping("/err")
   @ResponseBody
   public Object demo1(){
     int i = 1 / 0;
     return new Date();
   }
 
   @ExceptionHandler({RuntimeException.class})
   public ModelAndView fix(Exception ex){
     System.out.println(ex.getMessage());
     return new ModelAndView("error",new ModelMap("ex",ex.getMessage()));
   }
 }

优点:

缺点:

3. @ControllerAdvice 结合 @ExceptionHandler

这是 2. 的改进型,通过定义 @ControllerAdvice 类并在方法上标记 @ExceptionHandler ,达到了全局异常处理的目的:

 @ControllerAdvice
 public class TestController {
 
 
   @ExceptionHandler({RuntimeException.class})
   public ModelAndView fix(Exception ex){
     System.out.println(ex.getMessage());
     return new ModelAndView("error",new ModelMap("ex",ex.getMessage()));
   }
 }

优点:

缺点:

一般情况下也建议使用该方式进行异常处理。大多数情况下都是兼容的。

4. HandlerExceptionResolver 接口

实现 HandlerExceptionResolver 接口,这里我们继承其抽象实现 AbstractHandlerExceptionResolver :

 @Component
 public class RestResponseStatusExceptionResolver extends AbstractHandlerExceptionResolver {
 
   @Override
   protected ModelAndView doResolveException(
    HttpServletRequest request, 
    HttpServletResponse response, 
    Object handler, 
    Exception ex) {
     try {
       if (ex instanceof IllegalArgumentException) {
         return handleIllegalArgument((IllegalArgumentException) ex, response, handler);
       }
      //todo more exception
     } catch (Exception handlerException) {
        //todo 
     }
     return null;
   }
 
   private ModelAndView 
    handleIllegalArgument(IllegalArgumentException ex, HttpServletResponse response) 
    throws IOException {
     response.sendError(HttpServletResponse.SC_CONFLICT);
     String accept = request.getHeader(HttpHeaders.ACCEPT);
      //todo more response
     return new ModelAndView();
   }
 }

优点:

缺点:

5. Spring Boot 中的异常处理

如果你用的框架是 Spring Boot 。 我们还可以用它独特的处理方式。优点是屏蔽了低级的API,缺点也比较明显,无法捕捉到具体的异常。

5.1 实现 ErrorController

Spring Boot 在默认情况下,提供了 /error 映射来处理所有错误,在 Servlet 容器里注册了全局的错误页面(Whitelabel Error Page)并返回客户端。
通过实现 ErrorController 接口并注册为 Bean。这里不再举例。可参考 BasicErrorController

5.2 添加 ErrorAttributes

我们也可以添加 ErrorAttributes 类型的 Bean 来替换替换默认的异常处理。

 @Component
 public class MyCustomErrorAttributes extends DefaultErrorAttributes {
 
   @Override
   public Map<String, Object> getErrorAttributes(
    WebRequest webRequest, boolean includeStackTrace) {
     Map<String, Object> errorAttributes = 
      super.getErrorAttributes(webRequest, includeStackTrace);
     errorAttributes.put("locale", webRequest.getLocale()
       .toString());
     errorAttributes.remove("error");
 
     //todo your business
 
     return errorAttributes;
   }
 }

5.3 继承基类 BasicErrorController

Spring Boot 自动配置还提供了实现 ErrorController 接口异常处理的基类 BasicErrorController,默认是处理 text/html类型请求的错误,可以继承该基类自定义处理更多的请求类型,添加公共方法并使用 @RequestMapping 注解的 produce属性指定处理类型。

 @Component
 public class MyErrorController extends BasicErrorController {
 
   public MyErrorController(ErrorAttributes errorAttributes) {
     super(errorAttributes, new ErrorProperties());
   }
 
   @RequestMapping(produces = MediaType.APPLICATION_XML_VALUE)
   public ResponseEntity<Map<String, Object>> xmlError(HttpServletRequest request) {
     
   //todo your business
 
   }
 }

6. Spring 5 的 ResponseStatusException

另外在最新的 Spring 5 中你还可以通过 抛出 ResponseStatusException 异常来进行处理。

好处:

缺点:

以上就是关于总结Spring异常处理的内容,如果你们有学习到知识或者技能,可以把它分享出去让更多的人看到。

推荐阅读:
  1. Spring Cloud Stream总结
  2. Spring Cloud Stream异常处理

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

spring 异常处

上一篇:JQuery事件冒泡和默认行为的实现

下一篇:ng-repeat 指令用在一个对象数组上

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》