Skip to content

Commit 9edd7fe

Browse files
committed
11_11_error_status
1 parent bec01aa commit 9edd7fe

4 files changed

Lines changed: 35 additions & 32 deletions

File tree

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,28 @@
11
package ru.javawebinar.topjava.util.exception;
22

3+
import org.springframework.http.HttpStatus;
4+
35
public enum ErrorType {
4-
APP_ERROR("error.appError"),
5-
DATA_NOT_FOUND("error.dataNotFound"),
6-
DATA_ERROR("error.dataError"),
7-
VALIDATION_ERROR("error.validationError"),
8-
WRONG_REQUEST("error.wrongRequest");
6+
APP_ERROR("error.appError", HttpStatus.INTERNAL_SERVER_ERROR),
7+
// http://stackoverflow.com/a/22358422/548473
8+
DATA_NOT_FOUND("error.dataNotFound", HttpStatus.UNPROCESSABLE_ENTITY),
9+
DATA_ERROR("error.dataError", HttpStatus.CONFLICT),
10+
VALIDATION_ERROR("error.validationError", HttpStatus.UNPROCESSABLE_ENTITY),
11+
WRONG_REQUEST("error.wrongRequest", HttpStatus.BAD_REQUEST);
912

1013
private final String errorCode;
14+
private final HttpStatus status;
1115

12-
ErrorType(String errorCode) {
16+
ErrorType(String errorCode, HttpStatus status) {
1317
this.errorCode = errorCode;
18+
this.status = status;
1419
}
1520

1621
public String getErrorCode() {
1722
return errorCode;
1823
}
19-
}
24+
25+
public HttpStatus getStatus() {
26+
return status;
27+
}
28+
}

‎src/main/java/ru/javawebinar/topjava/web/ExceptionInfoHandler.java‎

Lines changed: 12 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,10 @@
66
import org.springframework.core.Ordered;
77
import org.springframework.core.annotation.Order;
88
import org.springframework.dao.DataIntegrityViolationException;
9-
import org.springframework.http.HttpStatus;
9+
import org.springframework.http.ResponseEntity;
1010
import org.springframework.http.converter.HttpMessageNotReadableException;
1111
import org.springframework.validation.BindException;
1212
import org.springframework.web.bind.annotation.ExceptionHandler;
13-
import org.springframework.web.bind.annotation.ResponseStatus;
1413
import org.springframework.web.bind.annotation.RestController;
1514
import org.springframework.web.bind.annotation.RestControllerAdvice;
1615
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
@@ -43,16 +42,13 @@ public ExceptionInfoHandler(MessageSourceAccessor messageSourceAccessor) {
4342
this.messageSourceAccessor = messageSourceAccessor;
4443
}
4544

46-
// http://stackoverflow.com/a/22358422/548473
47-
@ResponseStatus(HttpStatus.UNPROCESSABLE_ENTITY)
4845
@ExceptionHandler(NotFoundException.class)
49-
public ErrorInfo notFoundError(HttpServletRequest req, NotFoundException e) {
46+
public ResponseEntity<ErrorInfo> notFoundError(HttpServletRequest req, NotFoundException e) {
5047
return logAndGetErrorInfo(req, e, false, DATA_NOT_FOUND);
5148
}
5249

53-
@ResponseStatus(HttpStatus.CONFLICT) // 409
5450
@ExceptionHandler(DataIntegrityViolationException.class)
55-
public ErrorInfo conflict(HttpServletRequest req, DataIntegrityViolationException e) {
51+
public ResponseEntity<ErrorInfo> conflict(HttpServletRequest req, DataIntegrityViolationException e) {
5652
String rootMsg = ValidationUtil.getRootCause(e).getMessage();
5753
if (rootMsg != null) {
5854
String lowerCaseMsg = rootMsg.toLowerCase();
@@ -65,33 +61,32 @@ public ErrorInfo conflict(HttpServletRequest req, DataIntegrityViolationExceptio
6561
return logAndGetErrorInfo(req, e, true, DATA_ERROR);
6662
}
6763

68-
@ResponseStatus(value = HttpStatus.UNPROCESSABLE_ENTITY) // 422
6964
@ExceptionHandler(BindException.class)
70-
public ErrorInfo bindValidationError(HttpServletRequest req, BindException e) {
65+
public ResponseEntity<ErrorInfo> bindValidationError(HttpServletRequest req, BindException e) {
7166
String[] details = e.getBindingResult().getFieldErrors().stream()
7267
.map(messageSourceAccessor::getMessage)
7368
.toArray(String[]::new);
7469

7570
return logAndGetErrorInfo(req, e, false, VALIDATION_ERROR, details);
7671
}
7772

78-
@ResponseStatus(HttpStatus.UNPROCESSABLE_ENTITY) // 422
7973
@ExceptionHandler({IllegalRequestDataException.class, MethodArgumentTypeMismatchException.class, HttpMessageNotReadableException.class})
80-
public ErrorInfo validationError(HttpServletRequest req, Exception e) {
74+
public ResponseEntity<ErrorInfo> validationError(HttpServletRequest req, Exception e) {
8175
return logAndGetErrorInfo(req, e, false, VALIDATION_ERROR);
8276
}
8377

84-
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
8578
@ExceptionHandler(Exception.class)
86-
public ErrorInfo internalError(HttpServletRequest req, Exception e) {
79+
public ResponseEntity<ErrorInfo> internalError(HttpServletRequest req, Exception e) {
8780
return logAndGetErrorInfo(req, e, true, APP_ERROR);
8881
}
8982

9083
// https://stackoverflow.com/questions/538870/should-private-helper-methods-be-static-if-they-can-be-static
91-
private ErrorInfo logAndGetErrorInfo(HttpServletRequest req, Exception e, boolean logStackTrace, ErrorType errorType, String... details) {
84+
private ResponseEntity<ErrorInfo> logAndGetErrorInfo(HttpServletRequest req, Exception e, boolean logStackTrace, ErrorType errorType, String... details) {
9285
Throwable rootCause = ValidationUtil.logAndGetRootCause(log, req, e, logStackTrace, errorType);
93-
return new ErrorInfo(req.getRequestURL(), errorType,
94-
messageSourceAccessor.getMessage(errorType.getErrorCode()),
95-
details.length != 0 ? details : new String[]{ValidationUtil.getMessage(rootCause)});
86+
return ResponseEntity.status(errorType.getStatus())
87+
.body(new ErrorInfo(req.getRequestURL(), errorType,
88+
messageSourceAccessor.getMessage(errorType.getErrorCode()),
89+
details.length != 0 ? details : new String[]{ValidationUtil.getMessage(rootCause)})
90+
);
9691
}
9792
}

‎src/main/java/ru/javawebinar/topjava/web/GlobalExceptionHandler.java‎

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33
import org.slf4j.Logger;
44
import org.slf4j.LoggerFactory;
55
import org.springframework.context.support.MessageSourceAccessor;
6-
import org.springframework.http.HttpStatus;
76
import org.springframework.web.bind.annotation.ControllerAdvice;
87
import org.springframework.web.bind.annotation.ExceptionHandler;
98
import org.springframework.web.servlet.ModelAndView;
@@ -26,23 +25,23 @@ public GlobalExceptionHandler(MessageSourceAccessor messageSourceAccessor) {
2625

2726
@ExceptionHandler(NoHandlerFoundException.class)
2827
public ModelAndView wrongRequest(HttpServletRequest req, NoHandlerFoundException e) throws Exception {
29-
return logAndGetExceptionView(req, e, false, ErrorType.WRONG_REQUEST, HttpStatus.BAD_REQUEST);
28+
return logAndGetExceptionView(req, e, false, ErrorType.WRONG_REQUEST);
3029
}
3130

3231
@ExceptionHandler(Exception.class)
3332
public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
3433
log.error("Exception at request " + req.getRequestURL(), e);
35-
return logAndGetExceptionView(req, e, true, ErrorType.APP_ERROR, HttpStatus.INTERNAL_SERVER_ERROR);
34+
return logAndGetExceptionView(req, e, true, ErrorType.APP_ERROR);
3635
}
3736

38-
private ModelAndView logAndGetExceptionView(HttpServletRequest req, Exception e, boolean logException, ErrorType errorType, HttpStatus httpStatus) {
37+
private ModelAndView logAndGetExceptionView(HttpServletRequest req, Exception e, boolean logException, ErrorType errorType) {
3938
Throwable rootCause = ValidationUtil.logAndGetRootCause(log, req, e, logException, errorType);
4039

4140
ModelAndView mav = new ModelAndView("exception",
4241
Map.of("exception", rootCause, "message", ValidationUtil.getMessage(rootCause),
4342
"typeMessage", messageSourceAccessor.getMessage(errorType.getErrorCode()),
44-
"status", httpStatus));
45-
mav.setStatus(httpStatus);
43+
"status", errorType.getStatus()));
44+
mav.setStatus(errorType.getStatus());
4645
return mav;
4746
}
4847
}

‎src/test/java/ru/javawebinar/topjava/web/meal/MealRestControllerTest.java‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -163,7 +163,7 @@ void updateDuplicate() throws Exception {
163163
.content(JsonUtil.writeValue(invalid))
164164
.with(userHttpBasic(user)))
165165
.andDo(print())
166-
.andExpect(status().isConflict())
166+
.andExpect(status().isUnprocessableEntity())
167167
.andExpect(errorType(VALIDATION_ERROR))
168168
.andExpect(detailMessage(EXCEPTION_DUPLICATE_DATETIME));
169169
}
@@ -177,7 +177,7 @@ void createDuplicate() throws Exception {
177177
.content(JsonUtil.writeValue(invalid))
178178
.with(userHttpBasic(admin)))
179179
.andDo(print())
180-
.andExpect(status().isConflict())
180+
.andExpect(status().isUnprocessableEntity())
181181
.andExpect(errorType(VALIDATION_ERROR))
182182
.andExpect(detailMessage(EXCEPTION_DUPLICATE_DATETIME));
183183
}

0 commit comments

Comments
 (0)