47 lines
1.9 KiB
Java
47 lines
1.9 KiB
Java
package com.wecom.robot.config;
|
|
|
|
import com.wecom.robot.dto.ApiResponse;
|
|
import lombok.extern.slf4j.Slf4j;
|
|
import org.springframework.http.HttpStatus;
|
|
import org.springframework.validation.FieldError;
|
|
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 javax.validation.ConstraintViolation;
|
|
import javax.validation.ConstraintViolationException;
|
|
import java.util.stream.Collectors;
|
|
|
|
@Slf4j
|
|
@RestControllerAdvice
|
|
public class GlobalExceptionHandler {
|
|
|
|
@ExceptionHandler(MethodArgumentNotValidException.class)
|
|
@ResponseStatus(HttpStatus.BAD_REQUEST)
|
|
public ApiResponse<Void> handleValidationException(MethodArgumentNotValidException ex) {
|
|
String message = ex.getBindingResult().getFieldErrors().stream()
|
|
.map(FieldError::getDefaultMessage)
|
|
.collect(Collectors.joining("; "));
|
|
log.warn("参数校验失败: {}", message);
|
|
return ApiResponse.error(400, message);
|
|
}
|
|
|
|
@ExceptionHandler(ConstraintViolationException.class)
|
|
@ResponseStatus(HttpStatus.BAD_REQUEST)
|
|
public ApiResponse<Void> handleConstraintViolationException(ConstraintViolationException ex) {
|
|
String message = ex.getConstraintViolations().stream()
|
|
.map(ConstraintViolation::getMessage)
|
|
.collect(Collectors.joining("; "));
|
|
log.warn("约束校验失败: {}", message);
|
|
return ApiResponse.error(400, message);
|
|
}
|
|
|
|
@ExceptionHandler(Exception.class)
|
|
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
|
|
public ApiResponse<Void> handleException(Exception ex) {
|
|
log.error("服务器内部错误", ex);
|
|
return ApiResponse.error(500, "服务器内部错误");
|
|
}
|
|
}
|