1

我有一个带有 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的异常映射部分描述了以下捕获异常的途径。问题是这只捕获了一个特定的异常,我需要捕获很多。

我是否需要为每个异常创建一个新的异常路由,还是可以使用 处理所有错误get("/throwexception", (request, response) -> {

get("/throwexception", (request, response) -> {
    throw new YourCustomException();
});

exception(YourCustomException.class, (exception, request, response) -> {
    // Handle the exception here
});
4

0 回答 0