GlobalErrorController.java 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package com.simuwang.deploy.components;
  2. import com.simuwang.base.common.exception.ErrorInfo;
  3. import com.smppw.common.pojo.ResultVo;
  4. import jakarta.servlet.http.HttpServletRequest;
  5. import org.springframework.boot.web.servlet.error.ErrorController;
  6. import org.springframework.http.MediaType;
  7. import org.springframework.stereotype.Controller;
  8. import org.springframework.web.bind.annotation.RequestMapping;
  9. import org.springframework.web.bind.annotation.ResponseBody;
  10. import org.springframework.web.servlet.ModelAndView;
  11. /**
  12. * @author wangzaijun
  13. * @date 2023/8/12 15:46
  14. * @description 全局的错误信息处理
  15. */
  16. @Controller
  17. @RequestMapping("${server.error.path:/error}")
  18. public class GlobalErrorController implements ErrorController {
  19. private final static String DEFAULT_ERROR_VIEW = "error";//错误信息页
  20. private final ErrorInfoBuilder errorInfoBuilder;
  21. public GlobalErrorController(ErrorInfoBuilder errorInfoBuilder) {
  22. this.errorInfoBuilder = errorInfoBuilder;
  23. }
  24. /**
  25. * 情况1:若预期返回类型为text/html,则返回错误信息页(View).
  26. */
  27. @RequestMapping(produces = MediaType.TEXT_HTML_VALUE)
  28. public ModelAndView errorHtml(HttpServletRequest request) {
  29. return new ModelAndView(DEFAULT_ERROR_VIEW, "error", errorInfoBuilder.getErrorInfo(request));
  30. }
  31. /**
  32. * 情况2:其它预期类型 则返回详细的错误信息(JSON).
  33. */
  34. @RequestMapping
  35. @ResponseBody
  36. public ResultVo<?> error(HttpServletRequest request) {
  37. ErrorInfo errorInfo = errorInfoBuilder.getErrorInfo(request);
  38. return ResultVo.fail(errorInfo.getStatusCode(), errorInfo.getError());
  39. }
  40. }