use of io.helidon.webserver.HttpException in project helidon by oracle.
the class Main method errorHandling.
/**
* Request processing can cause error represented by {@link Throwable}. It is possible to register custom
* {@link io.helidon.webserver.ErrorHandler ErrorHandlers} for specific processing.
* <p>
* If error is not processed by a custom {@link io.helidon.webserver.ErrorHandler ErrorHandler} than default one is used.
* It respond with <i>HTTP 500 code</i> unless error is not represented
* by {@link HttpException HttpException}. In such case it reflects its content.
*/
public void errorHandling() {
Routing routing = Routing.builder().post("/compute", Handler.create(String.class, (req, res, str) -> {
int result = 100 / Integer.parseInt(str);
res.send(String.valueOf("100 / " + str + " = " + result));
})).error(Throwable.class, (req, res, ex) -> {
ex.printStackTrace(System.out);
req.next();
}).error(NumberFormatException.class, (req, res, ex) -> res.status(Http.Status.BAD_REQUEST_400).send()).error(ArithmeticException.class, (req, res, ex) -> res.status(Http.Status.PRECONDITION_FAILED_412).send()).build();
startServer(routing);
}
use of io.helidon.webserver.HttpException in project helidon by oracle.
the class FileBasedContentHandler method sendFile.
void sendFile(Http.RequestMethod method, Path pathParam, ServerRequest request, ServerResponse response, String welcomePage) throws IOException {
LOGGER.fine(() -> "Sending static content from file: " + pathParam);
Path path = pathParam;
// First doHandle a directory case
if (Files.isDirectory(path)) {
String rawFullPath = request.uri().getRawPath();
if (rawFullPath.endsWith("/")) {
// Try to found welcome file
path = resolveWelcomeFile(path, welcomePage);
} else {
// Or redirect to slash ended
redirect(request, response, rawFullPath + "/");
return;
}
}
// now it exists and is a file
if (!Files.isRegularFile(path) || !Files.isReadable(path) || Files.isHidden(path)) {
throw new HttpException("File is not accessible", Http.Status.FORBIDDEN_403);
}
// Caching headers support
try {
Instant lastMod = Files.getLastModifiedTime(path).toInstant();
processEtag(String.valueOf(lastMod.toEpochMilli()), request.headers(), response.headers());
processModifyHeaders(lastMod, request.headers(), response.headers());
} catch (IOException | SecurityException e) {
// Cannot get mod time or size - well, we cannot tell if it was modified or not. Don't support cache headers
}
processContentType(fileName(path), request.headers(), response.headers());
if (method == Http.Method.HEAD) {
response.send();
} else {
send(response, path);
}
}
use of io.helidon.webserver.HttpException in project helidon by oracle.
the class FileBasedContentHandler method detectType.
private MediaType detectType(String fileName, RequestHeaders requestHeaders) {
Objects.requireNonNull(fileName);
Objects.requireNonNull(requestHeaders);
// then check the type is accepted by the request
return findCustomMediaType(fileName).or(() -> MediaTypes.detectType(fileName).map(MediaType::parse)).map(it -> {
if (requestHeaders.isAccepted(it)) {
return it;
}
throw new HttpException("Media type " + it + " is not accepted by request", Http.Status.UNSUPPORTED_MEDIA_TYPE_415);
}).orElseGet(() -> {
List<MediaType> acceptedTypes = requestHeaders.acceptedTypes();
if (acceptedTypes.isEmpty()) {
return MediaType.APPLICATION_OCTET_STREAM;
} else {
return acceptedTypes.iterator().next();
}
});
}
use of io.helidon.webserver.HttpException in project helidon by oracle.
the class TestClientTest method advancingToDefaultErrorHandler.
@Test
public void advancingToDefaultErrorHandler() throws Exception {
StringBuffer sb = new StringBuffer();
HttpException exception = new HttpException("test-exception", Http.ResponseStatus.create(777));
Routing routing = Routing.builder().any((req, res) -> {
sb.append("any-");
req.next(exception);
}).error(IllegalStateException.class, (req, res, ex) -> {
fail("Should not be called");
}).error(Exception.class, (req, res, ex) -> {
sb.append("exceptionHandler-");
req.next(ex);
}).error(IllegalArgumentException.class, (req, res, ex) -> {
fail("Should not be called");
}).error(HttpException.class, (req, res, ex) -> {
sb.append("httpExceptionHandler-");
req.next();
}).error(Throwable.class, (req, res, ex) -> {
sb.append("throwableHandler");
req.next();
}).build();
TestResponse response = TestClient.create(routing).path("/anything/anywhere").get();
assertThat(sb.toString(), is("any-exceptionHandler-httpExceptionHandler-throwableHandler"));
assertThat(response.status().code(), is(777));
}
use of io.helidon.webserver.HttpException in project helidon by oracle.
the class StaticContentHandler method handle.
/**
* Do handle for GET and HEAD HTTP methods. It is filtering implementation, prefers {@code response.next()} before NOT_FOUND.
*
* @param method an HTTP method
* @param request an HTTP request
* @param response an HTTP response
*/
void handle(Http.RequestMethod method, ServerRequest request, ServerResponse response) {
// Check method
if ((method != Http.Method.GET) && (method != Http.Method.HEAD)) {
request.next();
return;
}
// Resolve path
String requestPath = request.path().toString();
if (requestPath.startsWith("/")) {
requestPath = requestPath.substring(1);
}
requestPath = resolvePathFunction.apply(requestPath);
// Call doHandle
try {
if (!doHandle(method, requestPath, request, response)) {
request.next();
}
} catch (HttpException httpException) {
if (httpException.status().code() == Http.Status.NOT_FOUND_404.code()) {
// Prefer to next() before NOT_FOUND
request.next();
} else {
throw httpException;
}
} catch (Exception e) {
LOGGER.log(Level.FINE, "Failed to access static resource", e);
throw new HttpException("Cannot access static resource!", Http.Status.INTERNAL_SERVER_ERROR_500, e);
}
}
Aggregations