Skip to content

Commit

Permalink
#871-refactor-log-error (#1007)
Browse files Browse the repository at this point in the history
* "#871-refactor-log-error"

* #871: fix code style checking

* #871: fix UT fail

* fix check style error
  • Loading branch information
DinhThaiVV authored Sep 11, 2024
1 parent 4a7c260 commit bff735f
Show file tree
Hide file tree
Showing 17 changed files with 663 additions and 516 deletions.
49 changes: 31 additions & 18 deletions cart/src/main/java/com/yas/cart/exception/ApiExceptionHandler.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import com.yas.cart.viewmodel.ErrorVm;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
Expand All @@ -19,46 +18,60 @@ public class ApiExceptionHandler {

@ExceptionHandler(NotFoundException.class)
public ResponseEntity<ErrorVm> handleNotFoundException(NotFoundException ex, WebRequest request) {
HttpStatus status = HttpStatus.NOT_FOUND;
String message = ex.getMessage();
ErrorVm errorVm = new ErrorVm(HttpStatus.NOT_FOUND.toString(), "NotFound", message);
log.warn(ERROR_LOG_FORMAT, this.getServletPath(request), 404, message);
log.debug(ex.toString());
return new ResponseEntity<>(errorVm, HttpStatus.NOT_FOUND);

return buildErrorResponse(status, message, null, ex, request, 404);
}

@ExceptionHandler(BadRequestException.class)
public ResponseEntity<ErrorVm> handleBadRequestException(BadRequestException ex, WebRequest request) {
String message = ex.getMessage();
ErrorVm errorVm = new ErrorVm(HttpStatus.BAD_REQUEST.toString(), "Bad request", message);
return ResponseEntity.badRequest().body(errorVm);
return handleBadRequest(ex, request);
}

@ExceptionHandler(MethodArgumentNotValidException.class)
protected ResponseEntity<ErrorVm> handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
HttpHeaders headers,
HttpStatus status, WebRequest request) {
protected ResponseEntity<ErrorVm> handleMethodArgumentNotValid(MethodArgumentNotValidException ex) {

HttpStatus status = HttpStatus.BAD_REQUEST;

List<String> errors = ex.getBindingResult()
.getFieldErrors()
.stream()
.map(error -> error.getField() + " " + error.getDefaultMessage())
.toList();

ErrorVm errorVm = new ErrorVm("400", "Bad Request", "Request information is not valid", errors);
return ResponseEntity.badRequest().body(errorVm);
return buildErrorResponse(status, "Request information is not valid", errors, ex, null, 0);
}

@ExceptionHandler(Exception.class)
protected ResponseEntity<ErrorVm> handleOtherException(Exception ex, WebRequest request) {
HttpStatus status = HttpStatus.INTERNAL_SERVER_ERROR;
String message = ex.getMessage();
ErrorVm errorVm = new ErrorVm(HttpStatus.INTERNAL_SERVER_ERROR.toString(),
HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(), message);
log.warn(ERROR_LOG_FORMAT, this.getServletPath(request), 500, message);
log.debug(ex.toString());
return new ResponseEntity<>(errorVm, HttpStatus.INTERNAL_SERVER_ERROR);

return buildErrorResponse(status, message, null, ex, request, 500);
}

private String getServletPath(WebRequest webRequest) {
ServletWebRequest servletRequest = (ServletWebRequest) webRequest;
return servletRequest.getRequest().getServletPath();
}

private ResponseEntity<ErrorVm> handleBadRequest(Exception ex, WebRequest request) {
HttpStatus status = HttpStatus.BAD_REQUEST;
String message = ex.getMessage();

return buildErrorResponse(status, message, null, ex, request, 400);
}

private ResponseEntity<ErrorVm> buildErrorResponse(HttpStatus status, String message, List<String> errors,
Exception ex, WebRequest request, int statusCode) {
ErrorVm errorVm =
new ErrorVm(status.toString(), status.getReasonPhrase(), message, errors);

if (request != null) {
log.error(ERROR_LOG_FORMAT, this.getServletPath(request), statusCode, message);
}
log.error(message, ex);
return ResponseEntity.status(status).body(errorVm);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,52 +17,59 @@ public class ApiExceptionHandler extends ResponseEntityExceptionHandler {

@ExceptionHandler(AccessDeniedException.class)
public ResponseEntity<ErrorVm> handleAccessDeniedException(AccessDeniedException ex, WebRequest request) {
HttpStatus status = HttpStatus.FORBIDDEN;
String message = ex.getMessage();
ErrorVm errorVm = new ErrorVm(HttpStatus.FORBIDDEN.toString(), "Access Denied", message);
log.warn(ERROR_LOG_FORMAT, this.getServletPath(request), 403, message);
log.debug(ex.toString());
return new ResponseEntity<>(errorVm, HttpStatus.FORBIDDEN);

return buildErrorResponse(status, message, ex, request, 403, "Access Denied");
}

@ExceptionHandler(NotFoundException.class)
public ResponseEntity<ErrorVm> handleNotFoundException(NotFoundException ex, WebRequest request) {
HttpStatus status = HttpStatus.NOT_FOUND;
String message = ex.getMessage();
ErrorVm errorVm = new ErrorVm(HttpStatus.NOT_FOUND.toString(), "NotFound", message);
log.warn(ERROR_LOG_FORMAT, this.getServletPath(request), 404, message);
log.debug(ex.toString());
return new ResponseEntity<>(errorVm, HttpStatus.NOT_FOUND);

return buildErrorResponse(status, message, ex, request, 404, "");
}

@ExceptionHandler(WrongEmailFormatException.class)
public ResponseEntity<ErrorVm> handleWrongEmailFormatException(WrongEmailFormatException ex, WebRequest request) {
String message = ex.getMessage();
ErrorVm errorVm = new ErrorVm(HttpStatus.BAD_REQUEST.toString(), "Bad request", message);
log.warn(ERROR_LOG_FORMAT, this.getServletPath(request), 400, message);
log.debug(ex.toString());
return ResponseEntity.badRequest().body(errorVm);
return handleBadRequest(ex, request);
}

@ExceptionHandler(CreateGuestUserException.class)
public ResponseEntity<ErrorVm> handleCreateGuestUserException(CreateGuestUserException ex, WebRequest request) {
String message = ex.getMessage();
ErrorVm errorVm = new ErrorVm(HttpStatus.BAD_REQUEST.toString(), "Bad request", message);
log.warn(ERROR_LOG_FORMAT, this.getServletPath(request), 500, message);
log.debug(ex.toString());
return ResponseEntity.badRequest().body(errorVm);
return handleBadRequest(ex, request);
}

@ExceptionHandler(Exception.class)
protected ResponseEntity<ErrorVm> handleOtherException(Exception ex, WebRequest request) {
HttpStatus status = HttpStatus.INTERNAL_SERVER_ERROR;
String message = ex.getMessage();
ErrorVm errorVm = new ErrorVm(HttpStatus.INTERNAL_SERVER_ERROR.toString(),
HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(), message);
log.warn(ERROR_LOG_FORMAT, this.getServletPath(request), 500, message);
log.debug(ex.toString());
return new ResponseEntity<>(errorVm, HttpStatus.INTERNAL_SERVER_ERROR);

return buildErrorResponse(status, message, ex, request, 500, "");
}

private String getServletPath(WebRequest webRequest) {
ServletWebRequest servletRequest = (ServletWebRequest) webRequest;
return servletRequest.getRequest().getServletPath();
}

private ResponseEntity<ErrorVm> handleBadRequest(Exception ex, WebRequest request) {
HttpStatus status = HttpStatus.BAD_REQUEST;
String message = ex.getMessage();

return buildErrorResponse(status, message, ex, request, 400, "");
}

private ResponseEntity<ErrorVm> buildErrorResponse(HttpStatus status, String message,
Exception ex, WebRequest request, int statusCode, String title) {
ErrorVm errorVm =
new ErrorVm(status.toString(), title.isEmpty() ? status.getReasonPhrase() : title, message);

if (request != null) {
log.error(ERROR_LOG_FORMAT, this.getServletPath(request), statusCode, message);
}
log.error(message, ex);
return ResponseEntity.status(status).body(errorVm);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,95 +24,98 @@ public class ApiExceptionHandler {

@ExceptionHandler(NotFoundException.class)
public ResponseEntity<ErrorVm> handleNotFoundException(NotFoundException ex, WebRequest request) {
HttpStatus status = HttpStatus.NOT_FOUND;
String message = ex.getMessage();
ErrorVm errorVm = new ErrorVm(HttpStatus.NOT_FOUND.toString(),
HttpStatus.NOT_FOUND.getReasonPhrase(), message);
log.warn(ERROR_LOG_FORMAT, this.getServletPath(request), 404, message);
log.debug(ex.toString());
return new ResponseEntity<>(errorVm, HttpStatus.NOT_FOUND);

return buildErrorResponse(status, message, null, ex, request, 404, "");
}

@ExceptionHandler(BadRequestException.class)
public ResponseEntity<ErrorVm> handleBadRequestException(BadRequestException ex, WebRequest request) {
String message = ex.getMessage();
ErrorVm errorVm = new ErrorVm(HttpStatus.BAD_REQUEST.toString(),
HttpStatus.BAD_REQUEST.getReasonPhrase(), message);
return ResponseEntity.badRequest().body(errorVm);
return handleBadRequest(ex, false, request);
}

@ExceptionHandler(MethodArgumentNotValidException.class)
protected ResponseEntity<ErrorVm> handleMethodArgumentNotValid(MethodArgumentNotValidException ex) {
HttpStatus status = HttpStatus.BAD_REQUEST;

List<String> errors = ex.getBindingResult()
.getFieldErrors()
.stream()
.map(error -> error.getField() + " " + error.getDefaultMessage())
.toList();

ErrorVm errorVm = new ErrorVm(HttpStatus.BAD_REQUEST.toString(),
HttpStatus.BAD_REQUEST.getReasonPhrase(), "Request information is not valid", errors);
return ResponseEntity.badRequest().body(errorVm);
return buildErrorResponse(status, "Request information is not valid", errors, ex, null, 0, "");
}

@ExceptionHandler({ConstraintViolationException.class})
public ResponseEntity<ErrorVm> handleConstraintViolation(ConstraintViolationException ex) {
List<String> errors = new ArrayList<>();
for (ConstraintViolation<?> violation : ex.getConstraintViolations()) {
errors.add(violation.getRootBeanClass().getName() + " "
+ violation.getPropertyPath() + ": " + violation.getMessage());
}
HttpStatus status = HttpStatus.BAD_REQUEST;

List<String> errors = ex.getConstraintViolations().stream()
.map(violation -> String.format("%s %s: %s",
violation.getRootBeanClass().getName(),
violation.getPropertyPath(),
violation.getMessage()))
.toList();

ErrorVm errorVm = new ErrorVm(HttpStatus.BAD_REQUEST.toString(),
HttpStatus.BAD_REQUEST.getReasonPhrase(), "Request information is not valid", errors);
return ResponseEntity.badRequest().body(errorVm);
return buildErrorResponse(status, "Request information is not valid", errors, ex, null, 0, "");
}

@ExceptionHandler(DataIntegrityViolationException.class)
public ResponseEntity<ErrorVm> handleDataIntegrityViolationException(DataIntegrityViolationException e) {
String message = NestedExceptionUtils.getMostSpecificCause(e).getMessage();
ErrorVm errorVm = new ErrorVm(HttpStatus.BAD_REQUEST.toString(),
HttpStatus.BAD_REQUEST.getReasonPhrase(), message);
return ResponseEntity.badRequest().body(errorVm);
public ResponseEntity<ErrorVm> handleDataIntegrityViolationException(DataIntegrityViolationException ex) {
return handleBadRequest(ex, true, null);
}

@ExceptionHandler(DuplicatedException.class)
protected ResponseEntity<ErrorVm> handleDuplicated(DuplicatedException e) {
ErrorVm errorVm = new ErrorVm(HttpStatus.BAD_REQUEST.toString(),
HttpStatus.BAD_REQUEST.getReasonPhrase(), e.getMessage());
return ResponseEntity.badRequest().body(errorVm);
protected ResponseEntity<ErrorVm> handleDuplicated(DuplicatedException ex) {
return handleBadRequest(ex, false, null);
}

@ExceptionHandler(AccessDeniedException.class)
public ResponseEntity<ErrorVm> handleAccessDeniedException(AccessDeniedException ex, WebRequest request) {
HttpStatus status = HttpStatus.FORBIDDEN;
String message = ex.getMessage();
ErrorVm errorVm = new ErrorVm(HttpStatus.FORBIDDEN.toString(), "Access Denied", message);
log.warn(ERROR_LOG_FORMAT, this.getServletPath(request), 403, message);
log.debug(ex.toString());
return new ResponseEntity<>(errorVm, HttpStatus.FORBIDDEN);

return buildErrorResponse(status, message, null, ex, request, 403, "Access Denied");
}

@ExceptionHandler(Exception.class)
protected ResponseEntity<ErrorVm> handleOtherException(Exception ex, WebRequest request) {
HttpStatus status = HttpStatus.INTERNAL_SERVER_ERROR;
String message = ex.getMessage();
ErrorVm errorVm = new ErrorVm(HttpStatus.INTERNAL_SERVER_ERROR.toString(),
HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(), message);
log.warn(ERROR_LOG_FORMAT, this.getServletPath(request), 500, message);
log.debug(ex.toString());
return new ResponseEntity<>(errorVm, HttpStatus.INTERNAL_SERVER_ERROR);

return buildErrorResponse(status, message, null, ex, request, 500, "");
}

@ExceptionHandler(StockExistingException.class)
public ResponseEntity<ErrorVm> handleStockExistingException(StockExistingException ex, WebRequest request) {
return handleBadRequest(ex, false, request);
}

private String getServletPath(WebRequest webRequest) {
ServletWebRequest servletRequest = (ServletWebRequest) webRequest;
return servletRequest.getRequest().getServletPath();
}

@ExceptionHandler(StockExistingException.class)
public ResponseEntity<ErrorVm> handleStockExistingException(StockExistingException ex, WebRequest request) {
String message = ex.getMessage();
ErrorVm errorVm = new ErrorVm(HttpStatus.BAD_REQUEST.toString(),
HttpStatus.BAD_REQUEST.getReasonPhrase(), message);
log.error(ERROR_LOG_FORMAT, this.getServletPath(request), 400, message);
log.debug(ex.toString());
return new ResponseEntity<>(errorVm, HttpStatus.BAD_REQUEST);
private ResponseEntity<ErrorVm> handleBadRequest(Exception ex, boolean isUsingNestedException, WebRequest request) {
HttpStatus status = HttpStatus.BAD_REQUEST;
String message =
isUsingNestedException ? NestedExceptionUtils.getMostSpecificCause(ex).getMessage() : ex.getMessage();

return buildErrorResponse(status, message, null, ex, request, 400, "");
}

private ResponseEntity<ErrorVm> buildErrorResponse(HttpStatus status, String message, List<String> errors,
Exception ex, WebRequest request, int statusCode, String title) {
ErrorVm errorVm =
new ErrorVm(status.toString(), title.isEmpty() ? status.getReasonPhrase() : title, message, errors);

if (request != null) {
log.error(ERROR_LOG_FORMAT, this.getServletPath(request), statusCode, message);
}
log.error(message, ex);
return ResponseEntity.status(status).body(errorVm);
}

}
Loading

0 comments on commit bff735f

Please sign in to comment.