GlobalExceptionHandler.java
1.84 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
package com.glsx.usedcar.advice;
import com.glsx.usedcar.resp.BaseResp;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.HibernateException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;
import java.util.stream.Collectors;
/**
* 全局异常处理器,捕获所有Controller层未处理的异常
*/
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
// 捕获所有未指定的异常(兜底)
@ExceptionHandler(Exception.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) // 明确返回500状态码
public BaseResp<Void> handleAllUncaughtException(Exception e) {
// 打印完整异常堆栈
log.error("全局捕获未处理异常:", e);
// 返回标准化错误响应
return BaseResp.fail("服务器内部错误:" + e.getMessage());
}
// 捕获参数校验异常(比如@Valid校验失败)
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public BaseResp<Void> handleValidationException(MethodArgumentNotValidException e) {
log.error("参数校验失败:", e);
String errorMsg = e.getBindingResult().getFieldErrors().stream()
.map(fieldError -> fieldError.getField() + ":" + fieldError.getDefaultMessage())
.collect(Collectors.joining(","));
return BaseResp.fail("参数错误:" + errorMsg);
}
// 捕获JPA/Hibernate相关异常
@ExceptionHandler(HibernateException.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public BaseResp<Void> handleHibernateException(HibernateException e) {
log.error("数据库查询异常:", e);
return BaseResp.fail("数据库操作失败:" + e.getMessage());
}
}