Skip to content

Commit

Permalink
Better error handling.
Browse files Browse the repository at this point in the history
  • Loading branch information
noboomu committed Jun 29, 2019
1 parent 452e82a commit c412faa
Show file tree
Hide file tree
Showing 7 changed files with 88 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ public class ServerException extends RuntimeException
*/
private static final long serialVersionUID = 8360356916374374408L;

private Integer status = 500;
private Integer status = Status.BAD_REQUEST.getStatusCode();

public ServerException(int status)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -694,12 +694,19 @@ protected void addClassMethodHandlers(TypeSpec.Builder typeBuilder, Class<?> cla
postProcess = String.format(".contentType(%s).",producesContentType);
}
}
methodBuilder.addCode("exchange.dispatch( () -> ");
methodBuilder.beginControlFlow("", "");


methodBuilder.addCode(
"$L.thenAcceptAsync( r -> io.sinistral.proteus.server.ServerResponse.response(r)" + postProcess + "send(this,$L), io.undertow.util.SameThreadExecutor.INSTANCE )\n\t.exceptionally( ex -> ",
"$L.thenAccept( r -> io.sinistral.proteus.server.ServerResponse.response(r)" + postProcess + "send(this,$L) )\n\t.exceptionally( ex -> ",
"response", "exchange");
methodBuilder.beginControlFlow("", "");
methodBuilder.addCode("\t\tthrow new java.util.concurrent.CompletionException(ex);\n\t");
methodBuilder.endControlFlow(")", "");

methodBuilder.endControlFlow(")", "");

} else {

methodBuilder.addStatement("exchange.getResponseHeaders().put($T.CONTENT_TYPE, $S)", Headers.class, producesContentType);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
import io.undertow.server.handlers.ResponseCodeHandler;
import io.undertow.server.handlers.cache.LRUCache;
import io.undertow.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Map;
Expand All @@ -22,6 +24,8 @@
*/
public class ProteusHandler implements HttpHandler
{
private static final Logger log = LoggerFactory.getLogger(ProteusHandler.class.getName());

private final PathMatcher<HttpHandler> pathMatcher = new PathMatcher<>();
private final Map<HttpString, PathTemplateMatcher<RoutingMatch>> matches = new CopyOnWriteMap<>();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,16 @@

import com.google.inject.Inject;
import com.typesafe.config.Config;
import io.sinistral.proteus.server.exceptions.ServerException;
import io.undertow.server.DefaultResponseListener;
import io.undertow.server.HttpHandler;
import io.undertow.server.HttpServerExchange;
import io.undertow.server.RoutingHandler;
import io.undertow.util.HeaderMap;
import io.undertow.util.HeaderValues;
import io.undertow.util.HttpString;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.stream.Collectors;
Expand All @@ -21,6 +24,8 @@
*/
public class ServerDefaultHttpHandler implements HttpHandler
{
private static final Logger log = LoggerFactory.getLogger(ServerDefaultHttpHandler.class);

protected final HeaderMap headers = new HeaderMap();

@Inject(optional = true)
Expand Down Expand Up @@ -61,7 +66,20 @@ public void handleRequest(final HttpServerExchange exchange) throws Exception
fiGlobal = headers.fiNextNonEmpty(fiGlobal);
}

next.handleRequest(exchange);
try {
next.handleRequest(exchange);
} catch (Exception e) {

exchange.putAttachment(DefaultResponseListener.EXCEPTION,e);

if(e instanceof ServerException)
{
ServerException serverException = (ServerException) e;
exchange.setStatusCode(serverException.getStatus());
}

defaultResponseListener.handleDefaultResponse(exchange);
}
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import io.sinistral.proteus.server.exceptions.ServerException;
import io.sinistral.proteus.server.predicates.ServerPredicates;
import io.undertow.server.DefaultResponseListener;
import io.undertow.server.HttpServerExchange;
Expand Down Expand Up @@ -47,9 +48,10 @@ public boolean handleDefaultResponse(HttpServerExchange exchange)
return false;
}

final int statusCode = exchange.getStatusCode();
int statusCode = exchange.getStatusCode();

if (statusCode >= 400) {

final Map<String, String> errorMap = new HashMap<>();
final String path = exchange.getRelativePath();
Throwable throwable = exchange.getAttachment(DefaultResponseListener.EXCEPTION);
Expand All @@ -58,6 +60,11 @@ public boolean handleDefaultResponse(HttpServerExchange exchange)
final String reason = StatusCodes.getReason(statusCode);

throwable = new Exception(reason);
} else if(throwable instanceof ServerException)
{
ServerException serverException = (ServerException) throwable;
exchange.setStatusCode(serverException.getStatus());
statusCode = serverException.getStatus();
}

errorMap.put("exceptionClass", throwable.getClass().getName());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableMap;
Expand All @@ -41,6 +42,7 @@
import io.sinistral.proteus.annotations.Chain;
import io.sinistral.proteus.server.ServerRequest;
import io.sinistral.proteus.server.ServerResponse;
import io.sinistral.proteus.server.exceptions.ServerException;
import io.sinistral.proteus.test.models.User;

import io.sinistral.proteus.test.wrappers.TestClassWrapper;
Expand All @@ -53,6 +55,7 @@
*/


@SuppressWarnings("ALL")
@Path("/tests")
@Produces((MediaType.APPLICATION_JSON))
@Consumes((MediaType.MEDIA_TYPE_WILDCARD))
Expand Down Expand Up @@ -372,7 +375,33 @@ public ServerResponse<Map<String,String>> debugEndpoint(ServerRequest request)
return response().badRequest(e);
}
}


// new ServerException("No entity found", Response.Status.NOT_FOUND);

@GET
@Path("response/error/404")
public ServerResponse<Void> notFoundError(ServerRequest request, @QueryParam("test") Optional<String> param ) throws Exception
{
if(!param.isPresent()) {
throw new ServerException("No entity found", Response.Status.NOT_FOUND);
}

return response().notFound();

}


@GET
@Path("response/error/401")
public ServerResponse<Void> unauthorizedError(ServerRequest request, @QueryParam("test") Optional<String> param ) throws Exception
{
if(!param.isPresent()) {
throw new ServerException("Unauthorized", Response.Status.UNAUTHORIZED);
}

return response().unauthorized();

}

@GET
@Path("response/debug/blocking")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
import java.util.stream.Collectors;
import java.util.stream.LongStream;

import io.restassured.RestAssured;
import org.apache.commons.io.IOUtils;
import org.hamcrest.CoreMatchers;
import org.junit.After;
Expand Down Expand Up @@ -56,6 +57,8 @@ public class TestControllerEndpoints
@Before
public void setUp()
{
RestAssured.enableLoggingOfRequestAndResponseIfValidationFails();

try
{
byte[] bytes = new byte[8388608];
Expand Down Expand Up @@ -456,6 +459,21 @@ public void responseParseTimestamp()
then().statusCode(200).and().body(containsString(ts.toString()));


}

@Test
public void notFound()
{
given().accept(ContentType.JSON).when().get("tests/response/error/404").then().statusCode(404).log().body().content(containsString("No entity found"));

}


@Test
public void unauthorized()
{
given().accept(ContentType.JSON).when().get("tests/response/error/401").then().statusCode(401).log().body().content(containsString("Unauthorized"));

}

@Test
Expand Down

0 comments on commit c412faa

Please sign in to comment.