简体   繁体   English

如何处理controller for Spring Boot REST API异常?

[英]How to handle Exception in controller for Spring Boot REST API?

I am confused of how I should handler the exception of the controller in a Spring Boot Rest API. Right now I throw some exception in my service classes like this:我很困惑我应该如何在 Spring 引导 Rest API 中处理 controller 的异常。现在我在我的服务类中抛出一些异常,如下所示:

public Optional<Item> getSpecificItem(Long itemId) throws Exception {

    return Optional.ofNullable(itemRepository.findById(itemId).
            orElseThrow(() -> new Exception("Item with that id doesn't exist")));
}

I don't know if this is the correct way to do it but it kind of works, I am open to criticism.我不知道这是否是正确的方法,但它有点管用,我愿意接受批评。 For the controller classes I don't know how it should look, I saw some example with @ControllerAdvice and exception for each controller and that looked kind of bad to me.对于 controller 类,我不知道它应该是什么样子,我看到了一些带有 @ControllerAdvice 的示例和每个 controller 的异常,这对我来说看起来有点糟糕。 Can I have a global exception class for all controllers?我可以为所有控制器设置一个全局异常 class 吗? Is it good practice?这是好的做法吗?

Saw some examples and I don't know if they were the correct way to do it.看到一些例子,我不知道他们是否是正确的做法。

@ControllerAdvice is good if you not use for general Exception. @ControllerAdvice如果您不用于一般异常则很好。 Example, if you define spec exception such as SkyIsRedException .例如,如果您定义规范异常,例如SkyIsRedException So, it will be throw anywhere it will catch.所以,它会被扔到它能抓住的任何地方。

@ControllerAdvice
public class ExampleAdvice {

    @ExceptionHandler(SkyIsRedException.class)
    @ResponseCode(HttpStatus.NOT_FOUND) // <- not required
    public void methodName1() { ... }

    @ExceptionHandler(SkyIsGreenException.class)
    public void methodName2() { ... }

}

And you can this @ExceptionHandler in controller too, so it will activate if any methods of controller will throw this SkyIsRedException .你也可以在 controller 中使用这个@ExceptionHandler ,所以如果 controller 的任何方法抛出这个SkyIsRedException ,它就会激活。

I not recommend use Exception for everything.我不建议对所有事情都使用Exception You are only harming yourself.你只是在伤害你自己。


UPDATE:更新:

// annotations
public class Controller {

    // annotations
    public Optional<Item> getSpecificItem(Long itemId) throws ItemNotExistException {
        return Optional.ofNullable(itemRepository.findById(itemId).
            orElseThrow(() -> new ItemNotExistException("Item with that id doesn't exist")));
    }

    // Controller specific exception handler, not central like @ControllerAdvice
    @ExceptionHandler(ItemNotExistException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public String itemNotExistExceptionHandler(ItemNotExistException ex) {
        return ex.getMessage(); // example
    {

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM