Written by:
David VlijmincxIntroduction
The @ControllerAdvice enables you to handle errors in a single place. This post will show you how to implement
the @ControllerAdvice to help you with exception handling inside a Spring application.
ControllerAdvice example
The following example shows a class annotated with the Spring @ControllerAdvice
annotation, meaning that it is used to handle exceptions.
The class contains two methods annotated with @ExceptionHandler
annotations that define how to handle specific exceptions thrown by controllers.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
| import jakarta.ws.rs.NotFoundException;
import org.springframework.http.HttpStatusCode;
import org.springframework.web.ErrorResponse;
import org.springframework.web.bind.annotation.*;
@ControllerAdvice
public class SomeControllerAdvice {
// Handle a single exception
@ExceptionHandler(UnsupportedOperationException.class)
ErrorResponse unsupported(UnsupportedOperationException e) {
System.out.println("An UnsupportedOperationException has happened");
return ErrorResponse.builder(e, HttpStatusCode.valueOf(500), "Operation is unsupported")
.build();
}
// Handle two or more exceptions
@ExceptionHandler({NotFoundException.class, NullPointerException.class})
ErrorResponse noResult(Exception e) {
System.out.println("An exception has happened");
return ErrorResponse.builder(e, HttpStatusCode.valueOf(500), "NullPointerException or NotFoundException")
.build();
}
}
|
The first method in the example is executed when an UnsupportedOperationException
occurs.
The second method has an @ExceptionHandler with an array of exception classes as input. Doing so you can handle multiple
kinds of exceptions with a single method. The second method is executed when a NotFoundException or NullPointerException has happened.
Controller to test the ControllerAdvice
To try out the previous example, you can use the following RestController. The controller has three endpoints
that will trigger the ExceptionHandlers in the class with the @ControllerAdvice
annotation.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
| @RestController
@RequestMapping(value = "/v1/some-endpoint")
public class SomeController {
@GetMapping("exception")
void throwException(){
throw new UnsupportedOperationException();
}
@GetMapping("not-found")
void throwNotFoundException() throws NotFoundException {
throw new NotFoundException("could not find");
}
@GetMapping("null-pointer")
void throwNullPointerException() {
throw new NullPointerException();
}
}
|
Conclusion
In this post, we have seen an example of how to implement @ControllerAdvice to handle a specific exception or multiple kinds of exceptions.