自定义错误控制器如何获取源URL路径

时间:2019-04-10 08:52:51

标签: spring-boot error-handling endpoint http-error

在我的春季启动项目中,我实现了一个CustomErrorController类,该类通过以下方式实现了接口ErrorController

@Controller
public class CustomErrorController implements ErrorController{


    @RequestMapping("/error")
    @ResponseBody
    public String handleError(HttpServletRequest request) {
        System.out.println("Request URL " + request.getRequestURL());
          Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
          Exception exception = (Exception) request.getAttribute("javax.servlet.error.exception");
          if(statusCode.equals(404)) {
              return String.format("<html><body><h2>Pagina non trovata</h2><div>Status code: <b>%s</b></div>"
                      + "<div>Exception Message: <b>La pagina cercata non esiste.</b></div><body></html>",
              statusCode, exception==null? "N/A": exception.getMessage());
          } else if (statusCode.equals(505)) {
              return String.format("<html><body><h2>Istanza non trovata</h2><div>Status code: <b>%s</b></div>"
                      + "<div>Exception Message: <b>L'istanza non è presente nel database</b></div><body></html>",
              statusCode, exception==null? "N/A": exception.getMessage());
          } else {
              return String.format("<html><body><h2>Errore</h2><div>Status code: <b>%s</b></div>"
                      + "<div>Exception Message: <b>%s</b></div><body></html>",
              statusCode, exception==null? "N/A": exception.getMessage());
          }

      }

    @Override
    public String getErrorPath() {

        return "/error";
    }

}

现在,我不仅要根据状态码,还要根据用户向其执行请求的端点发出不同的消息。我尝试使用方法request.getRequestURL(),但它返回http://localhost:9090/error。相反,如何获取“源URL”字符串?为了区别起见,假设地址http://localhost:9090/objectshttp://localhost:9090/otherobjects引发了错误。

0 个答案:

没有答案