123456789101112131415161718192021222324252627282930313233343536373839404142434445 |
- package com.simuwang.deploy.components;
- import com.simuwang.base.common.exception.ErrorInfo;
- import com.smppw.common.pojo.ResultVo;
- import jakarta.servlet.http.HttpServletRequest;
- 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 org.springframework.web.bind.annotation.ResponseBody;
- import org.springframework.web.servlet.ModelAndView;
- /**
- * @author wangzaijun
- * @date 2023/8/12 15:46
- * @description 全局的错误信息处理
- */
- @Controller
- @RequestMapping("${server.error.path:/error}")
- public class GlobalErrorController implements ErrorController {
- private final static String DEFAULT_ERROR_VIEW = "error";//错误信息页
- private final ErrorInfoBuilder errorInfoBuilder;
- public GlobalErrorController(ErrorInfoBuilder errorInfoBuilder) {
- this.errorInfoBuilder = errorInfoBuilder;
- }
- /**
- * 情况1:若预期返回类型为text/html,则返回错误信息页(View).
- */
- @RequestMapping(produces = MediaType.TEXT_HTML_VALUE)
- public ModelAndView errorHtml(HttpServletRequest request) {
- return new ModelAndView(DEFAULT_ERROR_VIEW, "error", errorInfoBuilder.getErrorInfo(request));
- }
- /**
- * 情况2:其它预期类型 则返回详细的错误信息(JSON).
- */
- @RequestMapping
- @ResponseBody
- public ResultVo<?> error(HttpServletRequest request) {
- ErrorInfo errorInfo = errorInfoBuilder.getErrorInfo(request);
- return ResultVo.fail(errorInfo.getStatusCode(), errorInfo.getError());
- }
- }
|