SpringBoot捕获全局异常(请求为Ajax和非Ajax)

  • Controller控制器:
import com.wyj.entity.vo.WebResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class AjaxErrorController {

    @RequestMapping("ajax")
    public String ajaxerror() {
        return "ajax";
    }

    @RequestMapping("/getAjaxerror")
    @ResponseBody
    public WebResponse getAjaxerror() {
        int a = 1 / 0;
        return WebResponse.ok();
    }

}

  • Handler全局异常处理器:
import com.wyj.entity.vo.WebResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 全局异常处理类
 */
@ControllerAdvice
public class WebAjaxExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    public Object errorHandler(HttpServletRequest request, HttpServletResponse response, Exception e) throws Exception {
        e.printStackTrace();
        //判断请求是否为Ajax请求
        if (isAjax(request)) { //如果是的话,就直接返回错误信息
            return WebResponse.errorException(e.getMessage());
        } else { //如果不是的话,就跳转到错误页面
            ModelAndView modelAndView = new ModelAndView();
            modelAndView.setViewName(“error”); //这里需要在templates文件夹下新建一个error.html文件用作错误页面
            return modelAndView;
        }
    }

    /**
     * 判断是否是Ajax请求
     *
     * @param request
     * @return
     */
    public boolean isAjax(HttpServletRequest request) {
        return (request.getHeader("X-Requested-With") != null &&
                "XMLHttpRequest".equals(request.getHeader("X-Requested-With").toString()));
    }

}

  • 总结:
    这里只是全局拦截Exception,如果还需要细分异常的话比如404:NoHandlerFoundException,只需要在@ExceptionHandler注解上参数为NoHandlerFoundException.class,并且在方法参数传入时注入NoHandlerFoundException

你可能感兴趣的:(SpringBoot)