我如何在 Spring Boot/MVC 中创建错误处理程序 (404, 500 ...) [英] How I create an error handler (404, 500...) in Spring Boot/MVC

查看:23
本文介绍了我如何在 Spring Boot/MVC 中创建错误处理程序 (404, 500 ...)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

几个小时以来,我试图在 Spring Boot/MVC 中创建一个自定义全局错误处理程序.我读了很多文章,什么都没有.

For some hours I'm trying to create a custom global error handler in Spring Boot/MVC. I've read a lot of articles and nothing.

这是我的错误类:

我尝试创建一个这样的类

I tried create a class like that

@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";
    }

}

推荐答案

你可以试试下面的代码:

You may try the following code:

@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 ...)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆