如何在Spring Boot / MVC中创建错误处理程序(404、500…)?

我试图在Spring Boot" title="Spring Boot">Spring Boot / MVC中创建CUSTOM全局错误处理程序。我读了很多文章,什么都没有…:/请帮我。

我尝试创建这样

@Controller

public class ErrorPagesController {

@RequestMapping("/404")

@ResponseStatus(HttpStatus.NOT_FOUND)

public String notFound() {

return "/error/404";

}

@RequestMapping("/403")

@ResponseStatus(HttpStatus.FORBIDDEN)

public String forbidden() {

return "/error/403";

}

@RequestMapping("/500")

@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)

public String internalServerError() {

return "/error/500";

}

}

我用这种方式:

`

@Configuration

public class ErrorConfig implements EmbeddedServletContainerCustomizer {

@Override

public void customize(ConfigurableEmbeddedServletContainer container) {

container.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/404"));

}

}

回答:

你可以尝试以下代码:

@ControllerAdvice

public class ExceptionController {

@ExceptionHandler(Exception.class)

public ModelAndView handleError(HttpServletRequest request, Exception e) {

Logger.getLogger(getClass().getName()).log(Level.SEVERE, "Request: " + request.getRequestURL() + " raised " + e);

return new ModelAndView("error");

}

@ExceptionHandler(NoHandlerFoundException.class)

public ModelAndView handleError404(HttpServletRequest request, Exception e) {

Logger.getLogger(getClass().getName()).log(Level.SEVERE, "Request: " + request.getRequestURL() + " raised " + e);

return new ModelAndView("404");

}

}

以上是 如何在Spring Boot / MVC中创建错误处理程序(404、500…)? 的全部内容, 来源链接: utcz.com/qa/398078.html

回到顶部