1.全局异常处理
//全局异常
@ControllerAdvice
public class GlobalExceptionHandler {
private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseBody
public String handleMethodArgumentNotValid(HttpServletResponse response, Exception e) {
response.setContentType("application/json;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
ObjectMapper objectMapper = new ObjectMapper();
//从异常中获得错误字段和信息
MethodArgumentNotValidException ex = (MethodArgumentNotValidException) e;
BindingResult bindingResult = ex.getBindingResult();
Map<String, Object> map = new HashMap<>();
for (FieldError error : bindingResult.getFieldErrors()) {
String field = error.getField();
String msg = error.getDefaultMessage();
map.put(field, msg);
}
try {
//参数出错返回code
response.getWriter().print(objectMapper.writeValueAsString(
ResultUtil.of(GlobalErrorCodeConstants.BAD_REQUEST.getCode()
, GlobalErrorCodeConstants.BAD_REQUEST.getMessage(), map)));
} catch (IOException exc) {
log.error("统一参数异常处理响应失败", exc);
}
return null;
}
}
2.Controller层中
import com.github.pagehelper.PageInfo;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.validation.constraints.NotNull;
/**
* @author cyb
* @date 2020/10/14
* @since 0.0.1
*/
@RestController
@RequestMapping("/demo")
public class DemoController {
@Autowired
private DemoService demoService;
@GetMapping("")
public Foo getFoo(Long fooId){
return demoService.getFoo(fooId);
}
//这里的Select.class只是个标记看第三段代码
@GetMapping("/listDemo")
public Result<PageInfo<FooVO>> getFooPage(@Validated(Select.class) FooPO fooPO,
@RequestParam("pageNum") Integer pageNum,
@RequestParam("pageSize") Integer pageSize){
return demoService.getFooPage(fooPO,pageNum,pageSize);
}
}
3.FooPO参数对象类
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.Range;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
/**
* @author cyb
* @date 2020/10/12
* @since 0.0.1
*/
//这个@Data注解是为了表示这是个完整的数据对象
@Data
public class FooPO {
//这里的groups就是进行了分组,比如,比如第二段代码中只有select那么@NotNull并不会生效
@Range(groups = { Select.class, Update.class,Delete.class},min = 0,message = "id参数错误")
@NotNull(groups = {Update.class, Delete.class}, message = "id不能为null")
private Long id;
}
4.存在的问题
无法在controller层对单个参数进行验证。比如
public class DemoController {
@Autowired
private DemoService demoService;
//这里的NotNull就不回生效。还在查询为什么。有没有好心人跟我说下相关文档在哪。
@GetMapping("")
public Foo getFoo(@Validated @NotNull Long fooId){
return demoService.getFoo(fooId);
}