Skip to content

Commit 2bc2c4c

Browse files
committed
global error handler added
1 parent 36f0374 commit 2bc2c4c

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package com.prs.services.exceptionHandler;
2+
3+
import java.util.stream.Collectors;
4+
5+
import org.apache.logging.log4j.LogManager;
6+
import org.apache.logging.log4j.Logger;
7+
import org.springframework.context.support.DefaultMessageSourceResolvable;
8+
import org.springframework.http.HttpStatus;
9+
import org.springframework.http.ResponseEntity;
10+
import org.springframework.web.bind.annotation.ControllerAdvice;
11+
import org.springframework.web.bind.annotation.ExceptionHandler;
12+
import org.springframework.web.bind.support.WebExchangeBindException;
13+
14+
@ControllerAdvice
15+
public class GlobalErrorHandler {
16+
17+
private static final Logger log = LogManager.getLogger(GlobalErrorHandler.class);
18+
19+
@ExceptionHandler(RuntimeException.class)
20+
public ResponseEntity<String> handleRuntimeException(RuntimeException ex){
21+
log.error("Exception caught in handleClientException : {} " ,ex.getMessage(), ex);
22+
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(ex.getMessage());
23+
}
24+
25+
@ExceptionHandler(WebExchangeBindException.class)
26+
public ResponseEntity<String> handleRequestBodyError(WebExchangeBindException ex){
27+
log.error("Exception caught in handleRequestBodyError : {} " ,ex.getMessage());
28+
var error = ex.getBindingResult().getAllErrors().stream()
29+
.map(DefaultMessageSourceResolvable::getDefaultMessage)
30+
.sorted()
31+
.collect(Collectors.joining(","));
32+
log.error("errorList : {}", error);
33+
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(error);
34+
}
35+
}

0 commit comments

Comments
 (0)