第七篇: springboot 全局异常配置

编写一个全局异常处理器  ExceptionHandler.java  html

@RestControllerAdvice
public class ExceptionHandler {


    @org.springframework.web.bind.annotation.ExceptionHandler(value = Exception.class)
    public ModelAndView error(Exception e, HttpServletRequest request) {
        System.out.println("捕获到异常:"+e.getMessage());
        System.out.println("url : "+request.getRequestURI());
        ModelAndView modelAndView=new ModelAndView();
        modelAndView.setViewName("error.html");
        return modelAndView;
    }

//    @org.springframework.web.bind.annotation.ExceptionHandler(value = Exception.class)
//    public String error(Exception e, HttpServletRequest request) {
//        System.out.println("捕获到异常:"+e.getMessage());
//        System.out.println("url : "+request.getRequestURI());
//        return  e.getMessage();
//    }

}

 

如上面的异常处理器,会拦截到全部异常,并进行处理java

一、@RestControllerAdvice 或者  @ControllerAdvice  注解 ,代表是当前类是全局异常处理器,若是是返回json数据 则用 RestControllerAdviceweb

二、@ExceptionHandler(value=Exception.class) 里面的 value 是拦截的异常类型,能够本身进行配置spring

三、返回数据能够是一个页面也能够是自定义的数据json

四、返回自定义异常界面,须要引入thymeleaf依赖,同时在 resource 目录下新建templates,并新建error.html
        <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>spring-boot

相关文章
相关标签/搜索