springboot的参数检验和异常处理的介绍

统一异常拦截处理:RestExceptionHandler

/**
 * Created by kaenry on 2016/9/20.
 * RestExceptionHandler
 */
@ControllerAdvice(annotations = RestController.class)
public class RestExceptionHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(RestExceptionHandler.class);

    @ExceptionHandler
    @ResponseBody
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    private  RestResult runtimeExceptionHandler(Exception e) {
        LOGGER.error("---------> huge error!", e);
        return RestResultGenerator.genErrorResult(ErrorCode.SERVER_ERROR);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    private  RestResult illegalParamsExceptionHandler(MethodArgumentNotValidException e) {
        LOGGER.error("---------> invalid request!", e);
        return RestResultGenerator.genErrorResult(ErrorCode.ILLEGAL_PARAMS);
    }

}

无论请求成功或失败统一返回RestResult,可自由定义,比如加上错误code或异常的多次处理以及日志啊什么的,代码都很简单,这里就不详细介绍了,返回的结果类似{"result":true,"message":null,"data":{"id":3,"username":"kaenry","password":"jianshu"}}spring-boot默认使用Jackson解析拼装json,如需要忽略null,加个注解即可:@JsonInclude(JsonInclude.Include.NON_NULL),fastjson默认开启。@Valid注解会验证属性,不通过会先交给BindingResult,如果没有这个参数则会抛出异常MethodArgumentNotValidException@ExceptionHandler捕捉到异常则会进入illegalParamsExceptionHandler方法返回结果:

{
  "result": false,
  "message": "request params invalid"
}

 

你可能感兴趣的:(springboot的参数检验和异常处理的介绍)