GlobalExceptionHandler.java
1.88 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
package com.xly.erp.common.exception;
import com.xly.erp.common.response.ApiResponse;
import com.xly.erp.common.response.ErrorCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
/** REQ-USR-004 账号锁定专用:把 cooldownSeconds 暴露在 data.cooldownSeconds */
@ExceptionHandler(AccountLockedException.class)
public ApiResponse<java.util.Map<String, Object>> handleAccountLocked(AccountLockedException e) {
log.warn("AccountLocked code={} cooldown={}s", e.getCode(), e.getCooldownSeconds());
java.util.Map<String, Object> data = java.util.Map.of("cooldownSeconds", e.getCooldownSeconds());
return new ApiResponse<>(e.getCode(), e.getMessage(), data, System.currentTimeMillis());
}
@ExceptionHandler(BizException.class)
public ApiResponse<Void> handleBiz(BizException e) {
log.warn("BizException code={} message={}", e.getCode(), e.getMessage());
return ApiResponse.fail(e.getCode(), e.getMessage());
}
@ExceptionHandler(MethodArgumentNotValidException.class)
public ApiResponse<Void> handleValidation(MethodArgumentNotValidException e) {
FieldError fe = e.getBindingResult().getFieldError();
String detail = fe == null
? ErrorCode.PARAM_INVALID.getMessage()
: fe.getField() + ": " + fe.getDefaultMessage();
return ApiResponse.fail(ErrorCode.PARAM_INVALID, detail);
}
@ExceptionHandler(Exception.class)
public ApiResponse<Void> handleAll(Exception e) {
log.error("Uncaught exception", e);
return ApiResponse.fail(ErrorCode.INTERNAL_ERROR);
}
}