UNPKG

764 BPlain TextView Raw
1import * as express from 'express';
2const IS_PRODUCTION = process.env.NODE_ENV === 'production';
3
4interface IErrorStack {
5 message: string;
6 stack: string[];
7}
8
9/**
10 * Turns an Error stack into a friendlier JSON value.
11 */
12function formatErrorStack(stack: string = ''): IErrorStack {
13 const lines = stack.split('\n');
14 const message = lines[0];
15 lines.shift();
16 return {
17 message,
18 stack: lines.map(line => line.trim()),
19 };
20}
21
22/**
23 * Sends an HTTP error to the client, with full stack details
24 * if running locally in development.
25 */
26export function sendError(code: number, res: express.Response, err: Error) {
27 const error = IS_PRODUCTION ? err.message : formatErrorStack(err.stack);
28 res.status(code).send({
29 status: code,
30 error,
31 });
32}