본문 바로가기
Back-end/Spring Boot + REST API

Spring boot - blog application (REST API) : Global Exception Handling

by javapp 자바앱 2022. 7. 5.
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

 

 

 

댓글