spring boot 全局统一格式返回自定义异常信息

首先我们要返回统一的格式信息的话,我们需要定义一个统一格式的类:

public class Result implements Serializable {

/** * 返回状态 */ private int status;

/** * 返回信息 */ private String msg;

/** * 返回数据 */ private Object data;

/**
 * 服务器内部错误时返回
 * 
 */
public static Result errResult() {

    Result result=new Result();
    result.setStatus(Constant.ERROR);
    result.setMsg(“ 服务器内部错误”);
    return result;
}

/**
 *处理失败时返回
 */
public static Result failResult(int status) {

    Result result = new Result();
    result.setStatus(status);
    result.setMsg(“操作失败”);
    return result;
}


/**
 * 处理正常时返回
 * [@return](https://my.oschina.net/u/556800)
 */
public static Result setSuccess(Object object) {
    Result result = new Result();
    result.setMsg(null);
    result.setStatus(Constant.OK);
    result.setData(object);
    return result;
}

[@Override](https://my.oschina.net/u/1162528)
public String toString() {
    return "Result{" +
            "states=" + status +
            ", msg='" + msg + '\'' +
            ", data=" + data +
            '}';
}

} 然后我们创建一个全局异常处理类:

/**

  • @description 全局异常处理类

  • @Author lihn

  • @Date 2017/6/8 */ @ControllerAdvice @ResponseBody @Slf4j public class CommonExceptionAdvice {

    /**

    • 400 - Bad Request */ @ResponseStatus(HttpStatus.BAD_REQUEST) @ExceptionHandler(MissingServletRequestParameterException.class)

public Result handleMissingServletRequestParameterException (MissingServletRequestParameterException e) { log.error("缺少请求参数", e); Result result = new Result(); result.setStatus(Constant.ERROR); result.setMsg(e.getMessage()); return result; } /** * 400 - Bad Request / @ResponseStatus(HttpStatus.BAD_REQUEST) @ExceptionHandler(HttpMessageNotReadableException.class) public Result handleHttpMessageNotReadableException(HttpMessageNotReadableException e) { log.error("参数解析失败", e); Result result = new Result(); result.setStatus(Constant.ERROR); result.setMsg(e.getMessage()); return result; } /* * 400 - Bad Request */ @ResponseStatus(HttpStatus.BAD_REQUEST) @ExceptionHandler(MethodArgumentNotValidException.class) public Result handleMethodArgumentNotValidException(MethodArgumentNotValidException e) { log.error("参数验证失败", e); BindingResult bindingResult = e.getBindingResult(); FieldError error = bindingResult.getFieldError(); String field = error.getField(); String code = error.getDefaultMessage();

    Result result = new Result();
    result.setStatus(Constant.ERROR);
    result.setMsg(code);
    return result;

}
/**
 * 400 - Bad Request
 */
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(BindException.class)
public Result handleBindException(BindException e) {
    log.error("参数绑定失败", e);
    BindingResult bindingResult = e.getBindingResult();
    FieldError error = bindingResult.getFieldError();
    String field = error.getField();
    String code = error.getDefaultMessage();
    Result result = new Result();
    result.setStatus(Constant.ERROR);
    result.setMsg(code);
    return result;
}
/**
 * 400 - Bad Request
 */
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(ConstraintViolationException.class)
public Result handleServiceException(ConstraintViolationException e) {
    log.error("参数验证失败", e);
    Set> violations = e.getConstraintViolations();
    ConstraintViolation violation = violations.iterator().next();
    String message = violation.getMessage();
    Result result = new Result();
    result.setStatus(Constant.ERROR);
    result.setMsg(message);
    return result;
}

/**
 * 400 - Bad Request
 */
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(ValidationException.class)
public Result handleValidationException(ValidationException e) {
    log.error("参数验证失败", e);
    Result result = new Result();
    result.setStatus(Constant.ERROR);
    result.setMsg(e.getMessage());
    return result;
}

/**
 * 405 - Method Not Allowed
 */
@ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
public Result handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
    log.error("不支持当前请求方法", e);
    Result result = new Result();
    result.setStatus(Constant.ERROR);
    result.setMsg(e.getMessage());
    return result;
}

/**
 * 415 - Unsupported Media Type
 */
@ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
@ExceptionHandler(HttpMediaTypeNotSupportedException.class)
public Result handleHttpMediaTypeNotSupportedException(Exception e) {
    log.error("不支持当前媒体类型", e);
    Result result = new Result();
    result.setStatus(Constant.ERROR);
    result.setMsg(e.getMessage());
    return result;
}

/**
 * 500 - Internal Server Error
 */
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ExceptionHandler(ServiceException.class)
public Result handleServiceException(ServiceException e) {
    log.error("业务逻辑异常", e);
    Result result = new Result();
    result.setStatus(Constant.ERROR);
    result.setMsg(e.getMessage());
    return result;
}

/**
 * 500 - Internal Server Error
 */
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ExceptionHandler(Exception.class)
public Result handleException(Exception e) {
    log.error("通用异常", e);
    Result result = new Result();
    result.setStatus(Constant.ERROR);
    result.setMsg(e.getMessage());
    return result;
}

/**
 * 操作数据库出现异常:名称重复,外键关联
 */
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ExceptionHandler(DataIntegrityViolationException.class)
public Result handleException(DataIntegrityViolationException e) {
    log.error("操作数据库出现异常:", e);
    Result result = new Result();
    result.setStatus(Constant.ERROR);
    result.setMsg(e.getMessage());
    return result;
}

} 再然后我没有封装一个我们自定义的类BizException继承RuntimeException的类: /**

  • @description 自定义异常

  • @Author lihn

  • @Date 2017/6/8 */ public class BizException extends RuntimeException { public BizException(@NonNls String message) { super(message); } } 到这里,我们的全局自定义异常就已经开发完了,下面开始测试:

    @RequestMapping(value = "/api/bucket/list", method = RequestMethod.GET) @ApiImplicitParams({@ApiImplicitParam(name = "X-Authorization", value = "Authorization token", required = true, dataType = "string", paramType = "header")}) @ApiOperation(value = "查询Bucket信息", notes = "告警等级 0 正常 1 警告 2 致命; marked: true为已修复,developerId:开发者ID" + "返回参数:status意义:200:成功;500:操作失败") public Result list(@RequestParam String developerId) {

     return Result.setSuccess(bizBucketService.getList(developerId));
    

    }

运行结果:

{ "status": 200, "msg": null, "data": [ { "id": "5ea4a5b6df2941119eec9956570c981d", "name": "12345", "permission": 1, "developerId": "12121", "swiftContainer": "1121121", "createDate": 1496719884000, "updateDate": null, "containSize": 3073301 }, { "id": "ed30b542943f4f3a9473897b5762380a", "name": "123", "permission": 1, "developerId": "12121", "swiftContainer": "1121121", "createDate": 1496719869000, "updateDate": null, "containSize": 0 }, { "id": "a1547c865762492badfdae6481806ae8", "name": "12", "permission": 1, "developerId": "12121", "swiftContainer": "1121121", "createDate": 1496719864000, "updateDate": null, "containSize": 0 } ] } 捕获异常信息:

{ "status": 500, "msg": "Could not read document: Unrecognized token 'qwewq': was expecting ('true', 'false' or 'null')\n at [Source: java.io.PushbackInputStream@44bad1e3; line: 1, column: 11]; nested exception is com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'qwewq': was expecting ('true', 'false' or 'null')\n at [Source: java.io.PushbackInputStream@44bad1e3; line: 1, column: 11]", "data": null }

好了,介绍结束了,喜欢这篇文章就点个赞吧

转载于:https://my.oschina.net/u/3420158/blog/918210

你可能感兴趣的:(spring boot 全局统一格式返回自定义异常信息)