引用之前的例子《Vert.x 4 Web REST CRUD接口应用》项目作为基础进行修改,创建一个自定义异常和异常拦截处理器。以实现
基于上一篇项目用到的类,新增了红色圈出来的类。
lombok
maven pom.xml 依赖模块添加以下依赖:
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
<version>1.18.34</version>
</dependency>
BusinessException
@EqualsAndHashCode(callSuper = true)
@Data
public class BusinessException extends RuntimeException{
private int code=480;
private String msg;
public BusinessException() {
this.msg="未知错误或空指针";
}
public BusinessException(int code, String msg) {
this.code = code;
this.msg = msg;
}
public BusinessException(String message) {
super(message);
this.msg=message;
}
public BusinessException(String message, Throwable cause) {
super(message, cause);
this.msg=message;
}
public BusinessException(Throwable cause) {
super(cause);
this.msg=cause.getMessage();
}
public BusinessException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
this.msg=message;
}
}
DefaultExceptionHandler
public class DefaultExceptionHandler implements Handler<RoutingContext> {
public DefaultExceptionHandler() {
}
@Override
public void handle(RoutingContext routingContext) {
Throwable throwable = routingContext.failure();
if (throwable == null) {
routingContext.response()
.setStatusCode(200)
.putHeader("content-type", "application/json; charset=utf-8")
.end(Json.encodeToBuffer(Result.fail(480,"未知错误")));
return;
}
if (throwable instanceof NullPointerException) {
routingContext.response()
.setStatusCode(200)
.putHeader("content-type", "application/json; charset=utf-8")
.end(Json.encodeToBuffer(Result.fail(480,"空指针")));
}
if (throwable instanceof BusinessException businessException) {
routingContext.response()
.setStatusCode(200)
.putHeader("content-type", "application/json; charset=utf-8")
.end(Json.encodeToBuffer(Result.fail(businessException.getCode(), businessException.getMsg())));
return;
}
//其他没有指明的统一输出500
routingContext.response()
.setStatusCode(200)
.putHeader("content-type", "application/json; charset=utf-8")
.end(Json.encodeToBuffer(Result.fail(500, "系统内部错误")));
}
public static DefaultExceptionHandler of() {
return new DefaultExceptionHandler();
}
}
聚焦代码
//必须加 last()排序到最后兜底
router.route().last().failureHandler(DefaultExceptionHandler.of());
/**
* 通过路径参数id获取单个产品
* @param routingContext 路由上下文
*/
private void getById(RoutingContext routingContext){
String id = routingContext.pathParam("id");
Whisky whisky = products.get(Integer.parseInt(id));
if (whisky == null) {
throw new BusinessException(481,"未找到相关产品信息:id-"+id);
}
routingContext.response()
.putHeader("content-type", "application/json; charset=utf-8")
.end(Json.encodePrettily(whisky));
}
使用postman 访问接口
从上图可以看到 参数为2 正确找到产品信息,参数为3则报错未找到,错误代码为我们指定的额481与预期效果一致。
输入一个非数字参数由于代码运行时候报错无法转换,而该异常并未指定特殊错误返回所以返回的全局默认错误500 + 系统内部错误,与预期效果一致。
http://blog.xqlee.com/article/2408121841039609.html