我有一个带有POST,PATCH,GET和DELETE路由的API。而且我必须在每个中创建try catch块以捕获各种可能的错误。我目前正在调用错误类
StandardError standardError = new StandardError("415");
package domainObjects;
import com.google.gson.annotations.Expose;
public class StandardError {
@Expose
String status;
@Expose
String source;
@Expose
String detail;
public StandardError(String errorCode){
switch(errorCode) {
case "409":
this.status = "409";
this.source = "/suppliers/";
this.detail = "Resource already exists";
break;
case "500":
this.status = "500";
this.source = "/suppliers/";
this.detail = "Unknown Error";
break;
case "415":
this.status = "415";
this.source = "/suppliers/";
this.detail = "Unsupported media type. Content Type: application/vnd.api+json required.";
break;
case "404":
this.status = "404";
this.source = "/suppliers/";
this.detail = "Resource does not exist";
break;
}
}
问题是每个路由方法都有大量复制。
spark上的Exception Mapping部分描述了捕获异常的以下路径。问题是这只是捕获一个特殊异常,我需要抓住很多。
我是否需要为每个例外创建一个新的例外路由,或者我可以使用get("/throwexception", (request, response) -> {
处理所有错误吗?
get("/throwexception", (request, response) -> {
throw new YourCustomException();
});
exception(YourCustomException.class, (exception, request, response) -> {
// Handle the exception here
});