SpringBoot 예외처리하기 - Exception Handling SpringBoot Exception Handling Basics
SpringBoot Exception Handling
When errors occur on the web, there are roughly three ways they can be handled:
- Error page
- HTTP Status 4XX errors, 5XX errors
- HTTP 200 + Error Message
Exception handling is already prepared in SpringBoot.
Let’s check the related annotations and see how to apply them.
@ControllerAdvice / @RestControllerAdvice
This can be used with View Resolver which handles page display functionality. In other words, it’s an annotation that can be applied to handle screens shown when errors occur, such as WhiteLabel Page.
@ExceptionHandler
When applied to a specific Controller, it provides functionality to catch all errors to that handler.
Let’s use the @Advice and @ExceptionHandler above to handle Exceptions.

Preparing for Exception Handling
Preparing Controller and Dto
Let’s create a Controller where Exceptions might occur for Exception handling.

The controller above uses User Dto. The User Dto was created as follows:

Now that preparation is complete, let’s think about cases where Exceptions might occur and create a package to handle those Exceptions.
The GET Mapping address receives name, password, email, phone, age as requestParams. Since each has the required option set to false, there’s no problem not sending data, but the code int my_number = 100 + age; at the bottom could throw an Exception if age is Null. Assuming this situation, I want to write an Exception Handler.
Creating Exception Class - Using @Advice
Classes annotated with @Advice are passed through in all cases where Exceptions occur. So I separated them into a separate class for handling Exceptions, and later it can be applied to each project domain.

- For REST API, I used
@RestControllerAdviceand applied@ExceptionHandlerto indicate that it’s an object to receive Exceptions - The function receives Exception as an argument to handle the corresponding Exception processing.
The code above has Exception.class as its value, which can handle all Exceptions. To check if it’s a related Exception, you can output e.getClass().getName() to find out what kind of Exception the current Exception is, and handle it separately according to that.
Since it’s currently an error related to Method Arguments due to RequestParam, let’s handle that error separately.
Creating Exception Class - Argument Exception
I’m going to create a more detailed version of @ExceptionHandler(value = Exception.class).
As mentioned above, since we’ll be using functionality related to Method Arguments, let’s find and apply the appropriate functionality.

The Exception function’s argument changed from Exception.class to MethodArgumentNotValidException.class.
You can’t memorize all Exception names, but you can find out the name of the corresponding Exception using e.getClass().getName() as shown above, and you can either handle it commonly or create separate handlers like we just did.
댓글남기기