forked from jooby-project/jooby
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathErrorHandler.java
More file actions
71 lines (65 loc) · 1.75 KB
/
ErrorHandler.java
File metadata and controls
71 lines (65 loc) · 1.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/**
* Jooby https://jooby.io
* Apache License Version 2.0 https://jooby.io/LICENSE.txt
* Copyright 2014 Edgar Espina
*/
package io.jooby;
import javax.annotation.Nonnull;
/**
* Catch and encode application errors.
*
* @author edgar
* @since 2.0.0
*/
public interface ErrorHandler {
/**
* Produces an error response using the given exception and status code.
*
* @param ctx Web context.
* @param cause Application error.
* @param code Status code.
*/
@Nonnull void apply(@Nonnull Context ctx, @Nonnull Throwable cause,
@Nonnull StatusCode code);
/**
* Chain this error handler with next and produces a new error handler.
*
* @param next Next error handler.
* @return A new error handler.
*/
@Nonnull default ErrorHandler then(@Nonnull ErrorHandler next) {
return (ctx, cause, statusCode) -> {
apply(ctx, cause, statusCode);
if (!ctx.isResponseStarted()) {
next.apply(ctx, cause, statusCode);
}
};
}
/**
* Build a line error message that describe the current web context and the status code.
*
* <pre>GET /path Status-Code Status-Reason</pre>
*
* @param ctx Web context.
* @param statusCode Status code.
* @return Single line message.
*/
static @Nonnull String errorMessage(@Nonnull Context ctx, @Nonnull StatusCode statusCode) {
return new StringBuilder()
.append(ctx.getMethod())
.append(" ")
.append(ctx.getRequestPath())
.append(" ")
.append(statusCode.value())
.append(" ")
.append(statusCode.reason())
.toString();
}
/**
* Creates a default error handler.
* @return Default error handler.
*/
static @Nonnull DefaultErrorHandler create() {
return new DefaultErrorHandler();
}
}