话不多说直接上干货:(每个注释都有详细解释,只需要有这个类就可以自动捕获处理控制层所有的异常了)
package com.quanzhan.excep;
import com.quanzhan.entity.CommonResult;
import org.springframework.http.HttpStatus;
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.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@ControllerAdvice
@ResponseBody //表示返回的对象,Spring会自动把该对象进行json转化,最后写入到Response中,并返回到异常页面。
public class GlobalExceptionHandler {
//定义错误时候跳转的视图.底层会自动拼接
public static final String ERROR_VIEW = "pages/error/error";
@ExceptionHandler(Exception.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public Object handleException(HttpServletRequest request,
HttpServletResponse response,
Exception e){
e.printStackTrace();//打印异常
// 是否ajax请求
if (isAjax(request)) {
//如果是ajax的异步请求就返回这个,CommonResult这个类是自定义的链式统一回复异步请求
return CommonResult.error().setErrorMessage(e.getMessage());
} else {
//如果是同步请求,就增加视图跳转,并携带参数
ModelAndView mav = new ModelAndView();
mav.addObject("exception", e);
mav.addObject("url", request.getRequestURL());
mav.setViewName(ERROR_VIEW);
return mav;
}
}
public static boolean isAjax(HttpServletRequest httpRequest){
return (httpRequest.getHeader("X-Requested-With") != null
&& "XMLHttpRequest"
.equals( httpRequest.getHeader("X-Requested-With")) );
}
}
看懂的小伙伴帮忙点个赞呗!