Handle error 404 with Spring controller

后端 未结 5 554
再見小時候
再見小時候 2020-11-29 07:00

I use @ExceptionHandler to handle exceptions thrown by my web app, in my case my app returns JSON response with HTTP status for error

5条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-29 07:13

    public final class ResourceNotFoundException extends RuntimeException {
    
    }
    
    
    @ControllerAdvice
    public class AppExceptionHandler {
        @ExceptionHandler(ResourceNotFoundException.class)
        @ResponseStatus(HttpStatus.NOT_FOUND)
        public String handleNotFound() {
            return "404";
        }
    }
    

    Just define an Exception, an ExceptionHandler, throw the Exception from your business code controller.

提交回复
热议问题