ErrorPagesController.java 7.2 KB
Newer Older
Y
yadong.zhang 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
/**
 * MIT License
 * Copyright (c) 2018 yadong.zhang
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.zyd.blog.controller;

Y
yadong.zhang 已提交
22
import lombok.extern.slf4j.Slf4j;
Y
yadong.zhang 已提交
23 24 25 26
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
智布道's avatar
智布道 已提交
27 28
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.boot.web.servlet.error.ErrorController;
Y
yadong.zhang 已提交
29 30 31 32 33
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestMapping;
智布道's avatar
智布道 已提交
34
import org.springframework.web.context.request.WebRequest;
Y
yadong.zhang 已提交
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 重写BasicErrorController,主要负责系统的异常页面的处理以及错误信息的显示
 * <p/>
 * 此处指需要记录
 * <p/>
 * 要注意,这个类里面的代码一定不能有异常或者潜在异常发生,否则可能会让程序陷入死循环。
 * <p/>
 *
 * @author yadong.zhang (yadong.zhang0415(a)gmail.com)
 * @website https://www.zhyd.me
 * @version 1.0
 * @date 2018/4/16 16:26
 * @since 1.0
 */
Y
yadong.zhang 已提交
55
@Slf4j
Y
yadong.zhang 已提交
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
@Controller
@RequestMapping("/error")
@EnableConfigurationProperties({ServerProperties.class})
public class ErrorPagesController implements ErrorController {

    private ErrorAttributes errorAttributes;

    @Autowired
    private ServerProperties serverProperties;

    /**
     * 初始化ExceptionController
     *
     * @param errorAttributes
     */
    @Autowired
    public ErrorPagesController(ErrorAttributes errorAttributes) {
        Assert.notNull(errorAttributes, "ErrorAttributes must not be null");
        this.errorAttributes = errorAttributes;
    }

    @RequestMapping("/404")
智布道's avatar
智布道 已提交
78
    public ModelAndView errorHtml404(HttpServletRequest request, HttpServletResponse response, WebRequest webRequest) {
Y
yadong.zhang 已提交
79
        response.setStatus(HttpStatus.NOT_FOUND.value());
智布道's avatar
智布道 已提交
80
        Map<String, Object> model = getErrorAttributes(webRequest, isIncludeStackTrace(request, MediaType.TEXT_HTML));
Y
yadong.zhang 已提交
81 82 83 84 85

        return new ModelAndView("error/404", model);
    }

    @RequestMapping("/403")
智布道's avatar
智布道 已提交
86
    public ModelAndView errorHtml403(HttpServletRequest request, HttpServletResponse response, WebRequest webRequest) {
Y
yadong.zhang 已提交
87 88
        response.setStatus(HttpStatus.FORBIDDEN.value());
        // 404拦截规则,如果是静态文件发生的404则不记录到DB
智布道's avatar
智布道 已提交
89
        Map<String, Object> model = getErrorAttributes(webRequest, isIncludeStackTrace(request, MediaType.TEXT_HTML));
90
        if (!String.valueOf(model.get("path")).contains(".")) {
Y
yadong.zhang 已提交
91 92 93 94 95 96
            model.put("status", HttpStatus.FORBIDDEN.value());
        }
        return new ModelAndView("error/403", model);
    }

    @RequestMapping("/400")
智布道's avatar
智布道 已提交
97
    public ModelAndView errorHtml400(HttpServletRequest request, HttpServletResponse response, WebRequest webRequest) {
Y
yadong.zhang 已提交
98
        response.setStatus(HttpStatus.BAD_REQUEST.value());
智布道's avatar
智布道 已提交
99
        Map<String, Object> model = getErrorAttributes(webRequest, isIncludeStackTrace(request, MediaType.TEXT_HTML));
Y
yadong.zhang 已提交
100 101 102 103
        return new ModelAndView("error/400", model);
    }

    @RequestMapping("/401")
智布道's avatar
智布道 已提交
104
    public ModelAndView errorHtml401(HttpServletRequest request, HttpServletResponse response, WebRequest webRequest) {
Y
yadong.zhang 已提交
105
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
智布道's avatar
智布道 已提交
106
        Map<String, Object> model = getErrorAttributes(webRequest, isIncludeStackTrace(request, MediaType.TEXT_HTML));
Y
yadong.zhang 已提交
107 108 109 110
        return new ModelAndView("error/401", model);
    }

    @RequestMapping("/500")
智布道's avatar
智布道 已提交
111
    public ModelAndView errorHtml500(HttpServletRequest request, HttpServletResponse response, WebRequest webRequest) {
Y
yadong.zhang 已提交
112
        response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
智布道's avatar
智布道 已提交
113
        Map<String, Object> model = getErrorAttributes(webRequest, isIncludeStackTrace(request, MediaType.TEXT_HTML));
Y
yadong.zhang 已提交
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
        return new ModelAndView("error/500", model);
    }

    /**
     * Determine if the stacktrace attribute should be included.
     *
     * @param request
     *         the source request
     * @param produces
     *         the media type produced (or {@code MediaType.ALL})
     * @return if the stacktrace attribute should be included
     */
    protected boolean isIncludeStackTrace(HttpServletRequest request,
                                          MediaType produces) {
        ErrorProperties.IncludeStacktrace include = this.serverProperties.getError().getIncludeStacktrace();
        if (include == ErrorProperties.IncludeStacktrace.ALWAYS) {
            return true;
        }
132
        return include == ErrorProperties.IncludeStacktrace.ON_TRACE_PARAM && getTraceParameter(request);
Y
yadong.zhang 已提交
133 134 135 136 137 138
    }


    /**
     * 获取错误的信息
     *
智布道's avatar
智布道 已提交
139
     * @param webRequest
Y
yadong.zhang 已提交
140 141 142
     * @param includeStackTrace
     * @return
     */
智布道's avatar
智布道 已提交
143
    private Map<String, Object> getErrorAttributes(WebRequest webRequest,
Y
yadong.zhang 已提交
144
                                                   boolean includeStackTrace) {
智布道's avatar
智布道 已提交
145
        return this.errorAttributes.getErrorAttributes(webRequest, includeStackTrace);
Y
yadong.zhang 已提交
146 147 148 149 150 151 152 153 154 155
    }

    /**
     * 是否包含trace
     *
     * @param request
     * @return
     */
    private boolean getTraceParameter(HttpServletRequest request) {
        String parameter = request.getParameter("trace");
156
        return parameter != null && !"false".equalsIgnoreCase(parameter);
Y
yadong.zhang 已提交
157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173
    }

    /**
     * 获取错误编码
     *
     * @param request
     * @return
     */
    private HttpStatus getStatus(HttpServletRequest request) {
        Integer statusCode = (Integer) request
                .getAttribute("javax.servlet.error.status_code");
        if (statusCode == null) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
        try {
            return HttpStatus.valueOf(statusCode);
        } catch (Exception ex) {
Y
yadong.zhang 已提交
174
            log.error("获取当前HttpStatus发生异常", ex);
Y
yadong.zhang 已提交
175 176 177 178 179 180 181 182 183 184 185 186 187 188
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
    }

    /**
     * 实现错误路径,暂时无用
     *
     * @return
     */
    @Override
    public String getErrorPath() {
        return "";
    }
}