validation捕获异常

好像需要在控制器启用校验才能捕获参数校验,即

@RestController
@Validated

----------------------分隔符-----------------------------

import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.xfstu.rbac.response.Response;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@RestControllerAdvice
public class GlobalError {

    // 捕获方法参数校验异常
    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseBody
    public ResponseEntity<Response<?>> constraintViolationExceptionHandler(ConstraintViolationException e){
        Set<ConstraintViolation<?>> message = e.getConstraintViolations();
        List<String> errorMessages = new ArrayList<>();
        message.stream().forEach(msg -> {
            errorMessages.add(msg.getMessage());
        });
        Response<String> errorResponse=Response.error(errorMessages.get(0),400);
        return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
    }

	// 捕获实体参数校验异常
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public ResponseEntity<Response<?>> handleBindException(MethodArgumentNotValidException ex) {
        String fieldError = ex.getBindingResult().getFieldError().getDefaultMessage();
        Response<String> errorResponse=Response.error(fieldError,400);
        return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
    }
	
	//全局异常
	@ExceptionHandler(Exception.class)
    public ResponseEntity<Response<?>> handleException(Exception ex) {
        System.out.println("异常类"+ex.getClass().getName());
        ex.printStackTrace();
        Response<?> errorResponse=Response.error("Something went wrong."+ex.getMessage(),500);
        return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
    }

}

不是专业的写法

posted @ 2024-05-13 21:35  小枫同学  阅读(52)  评论(0编辑  收藏  举报