728x90
REST API 에서 a custom error response를 생성하기
- Create ErrorDetails Class
- Create GlobalExceptionHandler Class
- Test using Postman Client
Create ErrorDetails Class
package com.springboot.blog.payload;
import java.util.Date;
import lombok.Getter;
@Getter
public class ErrorDetails
{
private Date timestamp;
private String message;
private String details;
public ErrorDetails(Date timestamp, String message, String details) {
super();
this.timestamp = timestamp;
this.message = message;
this.details = details;
}
}
더 많은 정보를 담고 싶다면,
then we can define thos fields inside of this class.
Create GlobalExceptionHandler Class
package com.springboot.blog.exception;
import com.springboot.blog.payload.ErrorDetails;
// To handle exceptions globally
// Will available for an auto detaction while component scanning.
@ControllerAdvice
public class GlobalExceptionHandler
{
// handle specific exceptions
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<ErrorDetails> handleResourceNotFoundException(ResourceNotFoundException exception, WebRequest webRequest)
{
ErrorDetails errorDetails = new ErrorDetails(new Date(), exception.getMessage(),webRequest.getDescription(false));
return new ResponseEntity<>(errorDetails, HttpStatus.NOT_FOUND);
}
@ExceptionHandler(BlogAPIException.class)
public ResponseEntity<ErrorDetails> handleBlogAPIException(BlogAPIException exception, WebRequest webRequest)
{
ErrorDetails errorDetails = new ErrorDetails(new Date(), exception.getMessage(),webRequest.getDescription(false));
return new ResponseEntity<>(errorDetails, HttpStatus.NOT_FOUND);
}
}
Test using Postman Client
Global Exception Handling
GlobalExceptionHandler
// global exceptions
@ExceptionHandler(Exception.class)
public ResponseEntity<ErrorDetails> handleGlobalException(Exception exception, WebRequest webRequest)
{
ErrorDetails errorDetails = new ErrorDetails(new Date(), exception.getMessage(),webRequest.getDescription(false));
return new ResponseEntity<>(errorDetails, HttpStatus.INTERNAL_SERVER_ERROR );
}
TEST
'Back-end > Spring Boot + REST API' 카테고리의 다른 글
Spring boot - blog application (REST API) : Securing REST APIs (0) | 2022.07.20 |
---|---|
Spring boot - blog application (REST API) : Validation @Valid (0) | 2022.07.06 |
Spring boot - blog application (REST API) : ModelMapper (0) | 2022.07.04 |
Spring boot - blog application (REST API) : Comment (0) | 2022.07.03 |
Spring boot - blog application (REST API) : Pagination and Sorting Support (0) | 2022.06.30 |
댓글