[Spring] Spring REST Exception Handling
Problem!
REST CRUD APIs(6)
- if wrong student id like out of number
You can handle the exception and return as JOSN
Spring REST Exception Handling
Development Process
- Create a custom error response class
- Create a custom exception class
- Update REST service to throw exception if student not found
- Add an exception handler method using @ExceptionHandler
Step 1: Create custom error response class
- The custom error response class will be sent back to client as JSON
- We will define as Java class(POJO)
- You can define any custom fields that you want to track
- Jackson will handle converting it to JSON
Step 2: Create custom student exception
- The custom student exception will used by our REST service
- In our code, if we can’t find student, then we’ll throw an exception
- Need to define a custom student exception class
Step 3: Update REST service to throw exception
Spring REST Exception Handling
Step 4: Add exception handler method
- Define exception handler method(s) with **@ExceptionHandler **annotation
- Exception handler will return a ResponseEntity
- ResponseEntity is a wrapper for the HTTP response object
- ResponseEntity provides fine-grained control to specify:
- HTTP status code, HTTP headers and Response body
출처 luv2code.com
댓글남기기