Validated验证异常处理
前台传来数据,非空验证,写if过于繁琐,用Validated验证
异常处理类:
@ControllerAdvice
@ResponseBody
public class ApcExceptionHandler {
@ExceptionHandler(Exception.class) //这里写捕获的异常类
public Response ex(HttpServletRequest request, Exception ex){
// ex.printStackTrace();
Map<String, String> map = new HashMap<>();
map.put("exception", ex.toString());
map.put("url", request.getRequestURL().toString());
return ResponseUtil.error(map);
}
}
返回实体类:
@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class Response {
private Integer code;
private String msg;
private Object data;
}
工具返回处理类:
public class ResponseUtil {
public static Response success(Object object){
Response resultVO = new Response();
resultVO.setCode(200);
resultVO.setMsg("成功");
resultVO.setData(object);
return resultVO;
}
public static Response error(Object object){
Response resultVO = new Response();
resultVO.setCode(404);
resultVO.setMsg("失败");
resultVO.setData(object);
return resultVO;
}
}
测试类:
@Validated
@RestController
public class UserController {
@GetMapping("/mapping")
public String login(@NotBlank String username,@NotBlank String password){
return "ok";
}
}
访问:
localhost:10001/mapping?username=zhangsan&password