opr-rest-api/src/main/java/com/goi/erp/common/exception/GlobalExceptionHandler.java

63 lines
2.5 KiB
Java

package com.goi.erp.common.exception;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(RuntimeException.class)
public ResponseEntity<?> handleRuntimeException(RuntimeException ex) {
Map<String, Object> body = new HashMap<>();
body.put("error", ex.getMessage());
body.put("timestamp", LocalDateTime.now());
body.put("status", HttpStatus.BAD_REQUEST.value());
return ResponseEntity.badRequest().body(body);
}
// 모든 예외 처리
@ExceptionHandler(Exception.class)
public ResponseEntity<Map<String, Object>> handleAllExceptions(Exception ex) {
Map<String, Object> body = new HashMap<>();
body.put("timestamp", LocalDateTime.now());
body.put("status", HttpStatus.INTERNAL_SERVER_ERROR.value());
body.put("error", "Internal Server Error");
body.put("message", ex.getMessage());
return new ResponseEntity<>(body, HttpStatus.INTERNAL_SERVER_ERROR);
}
// 권한 없음
@ExceptionHandler(AccessDeniedException.class)
public ResponseEntity<Map<String, Object>> handleAccessDenied(AccessDeniedException ex) {
Map<String, Object> body = new HashMap<>();
body.put("timestamp", LocalDateTime.now());
body.put("status", HttpStatus.FORBIDDEN.value());
body.put("error", "Forbidden");
body.put("message", ex.getMessage());
return new ResponseEntity<>(body, HttpStatus.FORBIDDEN);
}
//
@ExceptionHandler(JwtExpiredException.class)
public ResponseEntity<Map<String, String>> handleJwtExpired(JwtExpiredException ex) {
Map<String, String> body = Map.of("error", "JWT expired", "message", ex.getMessage());
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(body);
}
@ExceptionHandler(JwtInvalidException.class)
public ResponseEntity<Map<String, String>> handleJwtInvalid(JwtInvalidException ex) {
Map<String, String> body = Map.of("error", "Invalid JWT", "message", ex.getMessage());
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(body);
}
}