💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
~~~ package com.nobb.controller.advice; import com.nobb.util.Response; import org.springframework.validation.BindException; import org.springframework.validation.BindingResult; import org.springframework.validation.FieldError; import org.springframework.validation.ObjectError; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; import java.util.List; //@ControllerAdvice + @ResponseBody @RestControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(BindException.class) public Object handleMethodArgumentNotValidException(BindException e) { BindingResult exceptions = e.getBindingResult(); if (exceptions.hasErrors()) { List<ObjectError> errors = exceptions.getAllErrors(); if (!errors.isEmpty()) { // 这里列出了全部错误参数,按正常逻辑,只需要第一条错误即可 FieldError fieldError = (FieldError) errors.get(0); return Response.error(400, fieldError.getDefaultMessage()); } } return Response.error(400,"系统错误"); } } ~~~