Handling API route exceptions with java and spark

925 Views Asked by At

I have an API with routes for POST, PATCH, GET and DELETE. And I've had to create try catch blocks in each of these in order to catch a variety of possible errors. I currently make a call to an error class

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;

        }
    }

The problem is that there's a large amount of replication in each of the route methods.

The Exception Mapping section on spark describes the following route to catch exceptions. The issue being that this is only catching one particular exception, and I need to catch many.

Do I need to create a new exception route for each exception, or can I handle all the errors with get("/throwexception", (request, response) -> {?

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

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

There are 0 best solutions below