An error subclass with separate messages for server logs and HTTP responses.
It supports a suggested HTTP status code and convenience methods for sending a response via ExpressJS.
Currently only @numbereight/logger
loggers are supported.
if (!apiKey) {
return new ClientPresentableError({
clientMessage: `No API key was provided. You can add your API key in the 'Authorization' header as a bearer token.`,
clientHeaders: { 'WWW-Authenticate': `Bearer realm="My Realm", charset="UTF-8"` },
statusCode: 401,
serverMeta: {
url: req.originalUrl,
userAgent: req.get('User-Agent') || null,
},
});
}
const app = express();
app.use((
error: Error,
req: Request,
res: Response,
_next: NextFunction
) => {
const logger = new Logger();
const meta = {
path: req.path,
};
if (error instanceof ClientPresentableError) {
error.logAndSend(res, logger, meta);
return;
}
...
}
);
new ClientPresentableError({ clientMessage: string, clientHeaders?: { [header: string]: string }, statusCode: number, serverMessage?: string, serverMeta?: JSONishObject }) => ClientPresentableError
Create a ClientPresentableError.
-
clientMessage
the message to show the client, typically as an HTTP response. -
clientHeaders
(optional) headers to set in the HTTP response. -
statusCode
the suggested HTTP status code for the response. -
serverMessage
(optional) the message to log to the server, if different from the client message. -
serverMeta
(optional) additional metadata to log to the server.
Use the statusCode
to infer a suitable log level for the message.
- If >= 500, the level is
error
- If >= 400, the level is
warn
- Otherwise, the level is the default
Logs the serverMessage
to the given logger
, or uses the default logger from @numbereight/logging
if none is given.
A meta
object can be provided to add additional information to the log message.
Formats the serverMessage
and any given meta
as a loggable object.
Accepts an ExpressJS Response
object or an object that has a similar API and sends the clientMessage
in the body of the response. The headers will be updated according to clientHeaders
and the status code will be set by statusCode
.
#logAndSend(res: ExpressCompatibleResponse, logger: Logger = defaultLogger, meta: JSONishObject = {})
Performs a log operation followed by a send operation, as defined above. This is typically the most used method when handling a ClientPresentableError
.