Spring Boot 全局异常捕获

import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/*1,新建异常捕获类
 *2,类上添加注解@ControllerAdvice
 *3,在Class里面添加方法
 *4,方法上添加注解@ExceptionHandler(Exception.class)用来拦截相应的异常信息
 *5,如果返回的是View,方法返回值是ModelAndView
 *6,如果返回的是String或者Json数据,则需要加@ResponseBody注解
 */
@ControllerAdvice
public class GlobalDefaultExceptionHandler {    
    @ResponseBody
    @ExceptionHandler(Exception.class)
    public String defaultExceptionHandler(HttpServletRequest req,Exception e){
        return "Sorry,Server Error";
    }
}

 

posted @ 2019-04-18 09:48  Chris,Cai  阅读(186)  评论(0编辑  收藏  举报