GlobalExceptionHandler.java
2.37 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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package com.glsx.usedcar.advice;
import cn.hutool.core.util.StrUtil;
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.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.summerframework.core.exception.BusinessCodeException;
import java.util.stream.Collectors;
/**
* 全局异常处理器,捕获所有Controller层未处理的异常
*/
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
/**
* 捕获业务异常
* @author yangwei
* @since 2026/3/20 11:03
* @param e 业务异常
* @return com.glsx.usedcar.resp.BaseResp<java.lang.Void>
*/
@ExceptionHandler(BusinessCodeException.class)
public BaseResp<Void> handleBusinessException(BusinessCodeException e) {
log.error("业务异常", e);
return BaseResp.fail(StrUtil.toString(e.getCode()), e.getMessage());
}
// 捕获参数校验异常(比如@Valid校验失败)
@ExceptionHandler(MethodArgumentNotValidException.class)
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);
}
// 捕获所有未指定的异常(兜底)
@ExceptionHandler(Exception.class)
public BaseResp<Void> handleAllUncaughtException(Exception e) {
// 打印完整异常堆栈
log.error("全局捕获未处理异常:", e);
// 返回标准化错误响应
return BaseResp.fail("服务器内部错误:" + e.getMessage());
}
// 捕获JPA/Hibernate相关异常
@ExceptionHandler(HibernateException.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public BaseResp<Void> handleHibernateException(HibernateException e) {
log.error("数据库查询异常:", e);
return BaseResp.fail("数据库操作失败:" + e.getMessage());
}
}