简体   繁体   中英

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:

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. Can I have a global exception class for all controllers? 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. Example, if you define spec exception such as 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 .

I not recommend use Exception for everything. 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
    {

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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