如何在 Spring Boot 上替换 ErrorController 已弃用的功能?

e-i*_*128 14 java deprecated spring-boot

在 Spring boot 上有一个自定义错误控制器:

\n\n
package com.example.controllers;\n\nimport org.springframework.stereotype.Controller;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.boot.web.servlet.error.ErrorController;\nimport javax.servlet.http.HttpServletRequest;\n\n\n@Controller\npublic class CustomErrorController implements ErrorController\n{\n    @RequestMapping("/error")\n    public String handleError(HttpServletRequest request)\n    {\n        ...\n    }\n\n    @Override\n    public String getErrorPath()\n    {\n        return "/error";\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

但是,当编译时说:getErrorPath() in ErrorController has been deprecated. 好的,我找到了信息:使用server.error.path属性。好的,添加它application.properties并删除该函数,但现在显示:CustomErrorController is not abstract and does not override abstract method getErrorPath() in ErrorController, \xc2\xbfneed a deprecated function?。

\n\n

如何制作自定义错误控制器?,ErrorController需要getErrorPath但已弃用,正确的替代方案是什么?

\n

Tua*_*iAA 13

从 2.3.x 版本开始,Spring boot 已弃用此方法。只需返回 null,因为无论如何它都会被忽略。如果您想在完全删除该方法时防止将来出现编译错误,请不要使用 @Override 注释。如果需要,您还可以抑制弃用警告,但是,警告(也是 @Override 注释)有助于提醒您在删除方法时清理/修复代码。

@Controller
@RequestMapping("/error")
@SuppressWarnings("deprecation")
public class CustomErrorController implements ErrorController {

     public String error() {
        // handle error
        // ..
     }

     public String getErrorPath() {
         return null;
     }
}
Run Code Online (Sandbox Code Playgroud)


Lim*_*e莉茉 5

@Controller
public class CustomErrorController implements ErrorController {

    @RequestMapping("/error")
    public ModelAndView handleError(HttpServletResponse response) {
        int status = response.getStatus();
        if ( status == HttpStatus.NOT_FOUND.value()) {
            System.out.println("Error with code " + status + " Happened!");
            return new ModelAndView("error-404");
        } else if (status == HttpStatus.INTERNAL_SERVER_ERROR.value()) {
            System.out.println("Error with code " + status + " Happened!");
            return new ModelAndView("error-500");
        }
        System.out.println(status);
        return new ModelAndView("error");
    }
}
Run Code Online (Sandbox Code Playgroud)


Ole*_*iak 0

有一个@ControllerAdvice注释

@ControllerAdvice
public class MyErrorController {


   @ExceptionHandler(RuntimeException.class)
   public String|ResponseEntity|AnyOtherType handler(final RuntimeException e) {
     .. do handle ..
   }

   @ExceptionHandler({ Exception1.class, Exception2.class })
   public String multipleHandler(final Exception e) {

   }

}
Run Code Online (Sandbox Code Playgroud)