Fork me on GitHub

在SpringBoot中配置全局捕获异常

前言

之前写过一篇博客是使用spring利用HandlerExceptionResolver实现全局异常捕获

里面使用spring的HandlerExceptionResolver接口来实现全局的异常捕获,当时使用,但其实之后已经替换

当前项目中使用的是:@ControllerAdvice 、@ExceptionHandler通过这两个注解来实现全局的异常捕获

已经加入我的github模版中:https://github.com/LinkinStars/springBootTemplate

 

实现

创建GlobalExceptionResolver,实现如下:

import com.linkinstars.springBootTemplate.exception.ServiceException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 * 全局异常处理
 * @author LinkinStar
 */
@ControllerAdvice
public class GlobalExceptionResolver {

    @ExceptionHandler(value = ServiceException.class)
    public @ResponseBody String serviceCommonExceptionHandler(ServiceException e) {
        //对捕获的异常进行处理并打印日志等,之后返回json数据,方式与Controller相同
        return "{'code':-1}";
    }

    @ExceptionHandler(value = Exception.class)
    public ModelAndView exceptionHandler() {
        //当然也可以直接返回ModelAndView等类型,然后跳转相应的错误页面,这都根据实际的需要进行使用
        return new ModelAndView();
    }
}

其中ServiceException是自定义的异常

/**
 * 自定义异常
 * @author LinkinStar
 */
public class ServiceException extends RuntimeException{
}

spring会根据ExceptionHandler中的值进行匹配,如果你的一些异常没有被捕获,这里就会处理一些你没有捕获的异常

至于你需要返回一个页面还是需要返回一个json数据,这就看实际的业务场景了。

 

使用原因

在之前的博客中也提出,spring官方推荐这样的写法,但当时没有在意,在实际使用中出现问题后,最终还是采用了这样的方式,理由主要有下面几点:

1、使用注解的方式代码看上去更加的清晰。
2、对于自定义异常的捕获会很方便。
3、适用于对于返回json格式的情况(可以使用@ResponseBody注解方法对特定异常进行处理),使用HandlerExceptionResolver的话如果是ajax的请求,出现异常就会很尴尬,ajax并不认识ModelAndView。

 

posted @ 2018-03-06 23:43  LinkinStar  阅读(5039)  评论(0编辑  收藏  举报