一、HandlerExceptionResolver接口
package com.lw.utils; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.HandlerExceptionResolver; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @Configuration public class PlatformException implements HandlerExceptionResolver { @Override public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { ModelAndView mv = new ModelAndView(); //判断不同异常类型,做不同视图跳转 if(ex instanceof ArithmeticException){ mv.setViewName("error1"); } if(ex instanceof NullPointerException){ mv.setViewName("error2"); } return mv; } } 二、实现ErrorController接口
package com.lw.utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
@Controller
public class ErrorException implements ErrorController {
@Autowired
HttpServletRequest request;
@RequestMapping("/error")
public String getErrorPath() {
Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
switch (statusCode) {
case 404:
return "/404";
case 400:
return "/400";
default:
return "/500";
}
}
}