85 lines
2.8 KiB
Java
85 lines
2.8 KiB
Java
package com.designhub.exception;
|
|
|
|
import com.designhub.common.Result;
|
|
import com.designhub.common.ResultCode;
|
|
import lombok.extern.slf4j.Slf4j;
|
|
import org.springframework.validation.BindException;
|
|
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;
|
|
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
|
|
|
|
import java.util.stream.Collectors;
|
|
|
|
/**
|
|
* 全局异常处理器
|
|
*/
|
|
@Slf4j
|
|
@RestControllerAdvice
|
|
public class GlobalExceptionHandler {
|
|
|
|
/**
|
|
* 处理业务异常
|
|
*/
|
|
@ExceptionHandler(BusinessException.class)
|
|
public Result<?> handleBusinessException(BusinessException e) {
|
|
log.error("业务异常:{}", e.getMessage());
|
|
return Result.error(e.getCode(), e.getMessage());
|
|
}
|
|
|
|
/**
|
|
* 处理参数校验异常
|
|
*/
|
|
@ExceptionHandler(MethodArgumentNotValidException.class)
|
|
public Result<?> handleValidException(MethodArgumentNotValidException e) {
|
|
String message = e.getBindingResult().getFieldErrors()
|
|
.stream()
|
|
.map(FieldError::getDefaultMessage)
|
|
.collect(Collectors.joining(", "));
|
|
log.error("参数校验失败:{}", message);
|
|
return Result.error(ResultCode.BAD_REQUEST.getCode(), message);
|
|
}
|
|
|
|
/**
|
|
* 处理绑定异常
|
|
*/
|
|
@ExceptionHandler(BindException.class)
|
|
public Result<?> handleBindException(BindException e) {
|
|
String message = e.getFieldErrors()
|
|
.stream()
|
|
.map(FieldError::getDefaultMessage)
|
|
.collect(Collectors.joining(", "));
|
|
log.error("参数绑定失败:{}", message);
|
|
return Result.error(ResultCode.BAD_REQUEST.getCode(), message);
|
|
}
|
|
|
|
/**
|
|
* 处理参数类型不匹配异常
|
|
*/
|
|
@ExceptionHandler(MethodArgumentTypeMismatchException.class)
|
|
public Result<?> handleTypeMismatchException(MethodArgumentTypeMismatchException e) {
|
|
log.error("参数类型不匹配:{}", e.getMessage());
|
|
return Result.error(ResultCode.BAD_REQUEST.getCode(), "参数类型错误");
|
|
}
|
|
|
|
/**
|
|
* 处理IllegalArgumentException
|
|
*/
|
|
@ExceptionHandler(IllegalArgumentException.class)
|
|
public Result<?> handleIllegalArgumentException(IllegalArgumentException e) {
|
|
log.error("非法参数异常:{}", e.getMessage());
|
|
return Result.error(ResultCode.BAD_REQUEST.getCode(), e.getMessage());
|
|
}
|
|
|
|
/**
|
|
* 处理其他所有异常
|
|
*/
|
|
@ExceptionHandler(Exception.class)
|
|
public Result<?> handleException(Exception e) {
|
|
log.error("系统异常:", e);
|
|
return Result.error(ResultCode.ERROR.getCode(), "系统异常,请联系管理员");
|
|
}
|
|
}
|
|
|