-
Notifications
You must be signed in to change notification settings - Fork 72
Expand file tree
/
Copy pathControllerErrorAdvice.java
More file actions
67 lines (58 loc) · 2.42 KB
/
ControllerErrorAdvice.java
File metadata and controls
67 lines (58 loc) · 2.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package com.codesoom.assignment.controllers;
import com.codesoom.assignment.dto.ErrorResponse;
import com.codesoom.assignment.errors.*;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.Set;
@ResponseBody
@ControllerAdvice
public class ControllerErrorAdvice {
@ResponseStatus(HttpStatus.NOT_FOUND)
@ExceptionHandler(ProductNotFoundException.class)
public ErrorResponse handleProductNotFound() {
return new ErrorResponse("Product not found");
}
@ResponseStatus(HttpStatus.NOT_FOUND)
@ExceptionHandler(UserNotFoundException.class)
public ErrorResponse handleUserNotFound() {
return new ErrorResponse("User not found");
}
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(UserEmailDuplicationException.class)
public ErrorResponse handleUserEmailIsAlreadyExisted() {
return new ErrorResponse("User's email address is already existed");
}
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(LoginFailException.class)
public ErrorResponse handleLoginFailException() {
return new ErrorResponse("Log-in failed");
}
@ResponseBody
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(ConstraintViolationException.class)
public ErrorResponse handleConstraintValidateError(
ConstraintViolationException exception
) {
String messageTemplate = getViolatedMessage(exception);
return new ErrorResponse(messageTemplate);
}
@ResponseBody
@ResponseStatus(HttpStatus.FORBIDDEN)
@ExceptionHandler(UserNoPermission.class)
public ErrorResponse handleUserNoPermission(UserNoPermission exception) {
return new ErrorResponse(exception.getMessage());
}
private String getViolatedMessage(ConstraintViolationException exception) {
String messageTemplate = null;
Set<ConstraintViolation<?>> violations = exception.getConstraintViolations();
for (ConstraintViolation<?> violation : violations) {
messageTemplate = violation.getMessageTemplate();
}
return messageTemplate;
}
}