Skip to content

Commit fa75f6d

Browse files
committed
Add Error Handler
1 parent 6e10fb8 commit fa75f6d

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package br.com.spring.restful.errorhandler;
2+
3+
import org.springframework.http.HttpStatus;
4+
5+
public class GenericErrorResponse {
6+
7+
private int httpCode = 400;
8+
private String status = "";
9+
private String message = "";
10+
11+
public GenericErrorResponse(HttpStatus httpStatus, String message) {
12+
this.httpCode = httpStatus.value();
13+
this.status = httpStatus.getReasonPhrase();
14+
this.message = message;
15+
}
16+
17+
public int getHttpCode() {
18+
return httpCode;
19+
}
20+
21+
public void setHttpCode(int httpCode) {
22+
this.httpCode = httpCode;
23+
}
24+
25+
public String getStatus() {
26+
return status;
27+
}
28+
29+
public void setStatus(String status) {
30+
this.status = status;
31+
}
32+
33+
public String getMessage() {
34+
return message;
35+
}
36+
37+
public void setMessage(String message) {
38+
this.message = message;
39+
}
40+
41+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package br.com.spring.restful.errorhandler;
2+
3+
import org.springframework.core.Ordered;
4+
import org.springframework.core.annotation.Order;
5+
import org.springframework.http.HttpStatus;
6+
import org.springframework.http.ResponseEntity;
7+
import org.springframework.web.bind.annotation.ControllerAdvice;
8+
import org.springframework.web.bind.annotation.ExceptionHandler;
9+
10+
@ControllerAdvice
11+
@Order(Ordered.HIGHEST_PRECEDENCE)
12+
public class RestExceptionHandler {
13+
14+
@ExceptionHandler(Throwable.class)
15+
protected ResponseEntity<GenericErrorResponse> handleException(Throwable e) {
16+
GenericErrorResponse error = new GenericErrorResponse(HttpStatus.BAD_REQUEST, e.getMessage());
17+
return new ResponseEntity<GenericErrorResponse>(error, HttpStatus.BAD_REQUEST);
18+
}
19+
20+
}

0 commit comments

Comments
 (0)