springboot统一异常处理器

来源:互联网 发布:京东疯狂的美工倒计时 编辑:程序博客网 时间:2024/06/04 19:58

新建一个类
在class注解上@ControllerAdvice,
在方法上注解上@ExceptionHandler(value = Exception.class)

import org.springframework.web.bind.annotation.ControllerAdvice;import org.springframework.web.bind.annotation.ExceptionHandler;import javax.servlet.http.HttpServletRequest;/** * Created by LM on 2017/8/6. */@ControllerAdvice(basePackages = "demo1.e1")//basePackages 拦截指定包的异常public class GlobalDefaultExceptionHandler {    @ExceptionHandler(value = Exception.class)    public void defaultErrorHandler(HttpServletRequest req, Exception e)  {        //打印异常信息:        e.printStackTrace();        System.out.println("GlobalDefaultExceptionHandler.defaultErrorHandler()");    }}package demo1.e1;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;/** * Created by LM on 2017/8/6. */@Controller@RequestMappingpublic class aa {    @RequestMapping("/zeroException")    public int zeroException(){        return 100/0;    }    @RequestMapping("/")    public String hello(){        return "Hello world!";    }}
原创粉丝点击