diff --git a/restful-web-service/src/main/java/com/example/restfulwebservice/exception/CustomizedResponseEntityExceptionHandler.java b/restful-web-service/src/main/java/com/example/restfulwebservice/exception/CustomizedResponseEntityExceptionHandler.java new file mode 100644 index 00000000..650e73cc --- /dev/null +++ b/restful-web-service/src/main/java/com/example/restfulwebservice/exception/CustomizedResponseEntityExceptionHandler.java @@ -0,0 +1,33 @@ +package com.example.restfulwebservice.exception; + +import com.example.restfulwebservice.user.UserNotFoundException; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.context.request.WebRequest; +import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; + +import java.util.Date; + +@RestController +@ControllerAdvice +public class CustomizedResponseEntityExceptionHandler extends ResponseEntityExceptionHandler { + + @ExceptionHandler(Exception.class) + public final ResponseEntity handleAllException(Exception ex, WebRequest request) { + ExceptionResponse exceptionResponse = + new ExceptionResponse(new Date(), ex.getMessage(), request.getDescription(false)); + + return new ResponseEntity(exceptionResponse, HttpStatus.INTERNAL_SERVER_ERROR); + } + + @ExceptionHandler(UserNotFoundException.class) + public final ResponseEntity handleUserNotFoundException(Exception ex, WebRequest request) { + ExceptionResponse exceptionResponse = + new ExceptionResponse(new Date(), ex.getMessage(), request.getDescription(false)); + + return new ResponseEntity(exceptionResponse, HttpStatus.NOT_FOUND); + } +} diff --git a/restful-web-service/src/main/java/com/example/restfulwebservice/exception/ExceptionResponse.java b/restful-web-service/src/main/java/com/example/restfulwebservice/exception/ExceptionResponse.java new file mode 100644 index 00000000..35882db8 --- /dev/null +++ b/restful-web-service/src/main/java/com/example/restfulwebservice/exception/ExceptionResponse.java @@ -0,0 +1,16 @@ +package com.example.restfulwebservice.exception; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.Date; + +@Data +@AllArgsConstructor +@NoArgsConstructor +public class ExceptionResponse { + private Date timestamp; + private String message; + private String details; +}