GlobalExceptionHandler.java
1.38 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
package com.xly.erp.common.exception;
import com.xly.erp.common.response.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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;
@RestControllerAdvice
public class GlobalExceptionHandler {
private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
@ExceptionHandler(BizException.class)
public Result<Void> handleBiz(BizException e) {
log.warn("BizException code={} msg={}", e.getCode(), e.getMessage());
return Result.fail(e.getCode(), e.getMessage());
}
@ExceptionHandler(MethodArgumentNotValidException.class)
public Result<Void> handleValidation(MethodArgumentNotValidException e) {
FieldError fe = e.getBindingResult().getFieldError();
String msg = fe == null
? "参数校验失败"
: fe.getField() + ": " + fe.getDefaultMessage();
log.warn("ValidationException {}", msg);
return Result.fail(40001, msg);
}
@ExceptionHandler(Exception.class)
public Result<Void> handleAny(Exception e) {
log.error("Unhandled exception", e);
return Result.fail(50000, "系统繁忙");
}
}