代码


import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;


/**
 * Create by Martin 2018/5/27/027 21:51
 */
@Controller
public class ExceptionController implements ErrorController {

    private static final String ERROR_PATH = "/error";

    @RequestMapping(value=ERROR_PATH,produces = {MediaType.TEXT_HTML_VALUE})
    public String handleError(HttpServletRequest request){
        //获取statusCode:401,404,500
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        if(statusCode == 400){
            return "/pages/400";
        }else if(statusCode == 404){
            return "/pages/404";
        }else if(statusCode == 403){
            return "/pages/403";
        }else{
            return "/pages/500";
        }
    }

    @Override
    public String getErrorPath() {
        return null;
    }
}

讲一下

  • 主要是实现ErrorController接口,覆盖框架自带的处理类,实现自定义。