44 lines
1.4 KiB
Java
44 lines
1.4 KiB
Java
package com.example.demo.common;
|
|
|
|
import org.springframework.dao.DataAccessException;
|
|
import org.springframework.http.ResponseEntity;
|
|
import org.springframework.web.bind.annotation.ExceptionHandler;
|
|
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
|
|
|
import java.util.HashMap;
|
|
import java.util.Map;
|
|
|
|
@RestControllerAdvice
|
|
public class GlobalExceptionHandler {
|
|
|
|
private ResponseEntity<Map<String,Object>> badRequest(String message) {
|
|
Map<String,Object> body = new HashMap<>();
|
|
body.put("message", message);
|
|
return ResponseEntity.badRequest().body(body);
|
|
}
|
|
|
|
@ExceptionHandler(IllegalArgumentException.class)
|
|
public ResponseEntity<?> handleIllegalArgument(IllegalArgumentException ex) {
|
|
return badRequest(ex.getMessage());
|
|
}
|
|
|
|
@ExceptionHandler(IllegalStateException.class)
|
|
public ResponseEntity<?> handleIllegalState(IllegalStateException ex) {
|
|
return badRequest(ex.getMessage());
|
|
}
|
|
|
|
@ExceptionHandler(DataAccessException.class)
|
|
public ResponseEntity<?> handleDataAccess(DataAccessException ex) {
|
|
return badRequest("数据库操作失败");
|
|
}
|
|
|
|
@ExceptionHandler(Exception.class)
|
|
public ResponseEntity<?> handleAny(Exception ex) {
|
|
Map<String,Object> body = new HashMap<>();
|
|
body.put("message", ex.getMessage() == null ? "Internal Server Error" : ex.getMessage());
|
|
return ResponseEntity.status(500).body(body);
|
|
}
|
|
}
|
|
|
|
|