Java 如何在 Spring Boot/MVC 中创建错误处理程序 (404, 500...)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38777723/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 20:38:30  来源:igfitidea点击:

How I create an error handler (404, 500...) in Spring Boot/MVC

javaspringspring-mvcspring-boot

提问by Ismael Ezequiel

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

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

That is my error class:

那是我的错误类:

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

}

采纳答案by Mehmet Ali

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

回答by Arash

@ControllerAdvice
 public class ErrorHandler {

public RestErrorHandler() {
}

@ExceptionHandler(YourException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public XXX processException(Exception ex){}

You need a class like this. Add a method for each exception, and annotate it as you please - @ResponseBody etc.

你需要这样的课程。为每个异常添加一个方法,并根据需要对其进行注释 - @ResponseBody 等。

回答by Achille_vanhoutte

Hope this will help: Create a class say: NoProductsFoundException that extends runtimexception.

希望这会有所帮助:创建一个类说:NoProductsFoundException 扩展运行时异常。

    import org.springframework.http.HttpStatus;
    import org.springframework.web.bind.annotation.ResponseStatus;

    @ResponseStatus(value=HttpStatus.NOT_FOUND, reason="No products found under this category")
    public class NoProductsFoundException extends RuntimeException{

    private static final long serialVersionUID =3935230281455340039L;
    }

Then in your productcontroller:

然后在您的产品控制器中:

    @RequestMapping("/{category}")
    public String getProductsByCategory(Model
    model,@PathVariable("category") String category) {

   List<Product> products = productService.getProductsByCategory(category);

   if (products == null || products.isEmpty()) {
   throw new NoProductsFoundException ();
   }
   model.addAttribute("products", products);
   return "products";
}

enter image description here

在此处输入图片说明

回答by Alex Fernandez

Additional to @ArashYou could add a new BaseControllerclass that you can extends,that handles the conversion from exception to http response.

除了@Arash,您还可以添加一个BaseController可以扩展的新类,用于处理从异常到http response.

     import com.alexfrndz.pojo.ErrorResponse;
     import com.alexfrndz.pojo.Error;
     import com.alexfrndz.pojo.exceptions.NotFoundException;
     import org.springframework.http.HttpStatus;
     import org.springframework.http.ResponseEntity;
     import org.springframework.web.bind.annotation.ExceptionHandler;
     import org.springframework.web.bind.annotation.ResponseBody;
     import org.springframework.web.bind.annotation.ResponseStatus;

     import javax.persistence.NoResultException;
     import javax.servlet.http.HttpServletRequest;
     import java.util.List;

     @Slf4j
     public class BaseController {

    @ExceptionHandler(NoResultException.class)
    public ResponseEntity<Exception> handleNoResultException(
            NoResultException nre) {
        log.error("> handleNoResultException");
        log.error("- NoResultException: ", nre);
        log.error("< handleNoResultException");
        return new ResponseEntity<Exception>(HttpStatus.NOT_FOUND);
    }


    @ExceptionHandler(Exception.class)
    public ResponseEntity<Exception> handleException(Exception e) {
        log.error("> handleException");
        log.error("- Exception: ", e);
        log.error("< handleException");
        return new ResponseEntity<Exception>(e,
                HttpStatus.INTERNAL_SERVER_ERROR);
    }

    @ExceptionHandler(NotFoundException.class)
    @ResponseStatus(value = HttpStatus.NOT_FOUND)
    @ResponseBody
    public ErrorResponse handleNotFoundError(HttpServletRequest req, NotFoundException exception) {
        List<Error> errors = Lists.newArrayList();
        errors.add(new Error(String.valueOf(exception.getCode()), exception.getMessage()));
        return new ErrorResponse(errors);
    }
   }

回答by Eduardo

Update for spring boot

弹簧靴的更新

Custom error pages

自定义错误页面

If you want to display a custom HTML error page for a given status code, you add a file to an /error folder. Error pages can either be static HTML (i.e. added under any of the static resource folders) or built using templates. The name of the file should be the exact status code or a series mask.

如果要为给定状态代码显示自定义 HTML 错误页面,请将文件添加到 /error 文件夹。错误页面可以是静态 HTML(即添加到任何静态资源文件夹下)或使用模板构建。文件的名称应该是确切的状态代码或系列掩码。

For example, to map 404 to a static HTML file, your folder structure would look like this

例如,要将 404 映射到静态 HTML 文件,您的文件夹结构将如下所示

src/
 +- main/
     +- java/
     |   + <source code>
     +- resources/
         +- public/
             +- error/
             |   +- 404.html
             +- <other public assets>

Source

来源