Skip to content

Instantly share code, notes, and snippets.

@jancimajek
Last active July 9, 2019 20:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jancimajek/f21eeb31ff9d100c8142a0b0f3a07842 to your computer and use it in GitHub Desktop.
Save jancimajek/f21eeb31ff9d100c8142a0b0f3a07842 to your computer and use it in GitHub Desktop.
Async error handling
import debug from 'debug';
import express, { NextFunction, Request, Response } from 'express';
const testRouter = express.Router();
const delay = async (wait: number, label: string) =>
new Promise(resolve => {
debug('yncx:delay:start')({ wait, label });
setTimeout(() => {
debug('yncx:delay:end')({ wait, label });
resolve(wait);
}, wait);
});
const withCatch = (
f: (...args: any[]) => Promise<any>,
): ((...args: any[]) => Promise<any>) => (...args) =>
f(...args).catch(error => {
throw error;
});
async function doSomeAsyncTask(wait: number) {
debug('yncx:doSomeAsyncTask')({ wait });
await delay(wait, 'doSomeAsyncTask');
debug('yncx:doSomeAsyncTask')('Throwing error');
throw new Error('Test async error');
}
async function test() {
debug('yncx:test')({});
const promiseIcanWaitFor = withCatch(doSomeAsyncTask)(100);
const somethingElse = delay(200, 'test:somethingElse');
const result = await Promise.all([promiseIcanWaitFor, somethingElse]);
debug('yncx:test:result')({ result });
}
const testMiddleware = async (
req: Request,
res: Response,
next: NextFunction,
) => {
try {
await test();
debug('yncx:testMiddleware')('OK');
next();
} catch (error) {
debug('yncx:testMiddleware')('Caught error');
// You'd normally pass this onto the next() error handler here:
res.status(500).send({
error: error.message,
});
}
};
testRouter.use(testMiddleware);
testRouter.get('/async-error-test', async (req: Request, res: Response) => {
return res.sendStatus(200);
});
export default testRouter;
curl -i http://localhost:8080/async-error-test
HTTP/1.1 500 Internal Server Error
X-Powered-By: Express
Content-Type: application/json; charset=utf-8
Content-Length: 28
ETag: W/"1c-3N4A5kSM7ex++ACAGIND7W0R29c"
Date: Tue, 09 Jul 2019 20:43:02 GMT
Connection: keep-alive
{"error":"Test async error"}
yncx:test {} +0ms
yncx:doSomeAsyncTask { wait: 100 } +0ms
yncx:delay:start { wait: 100, label: 'doSomeAsyncTask' } +0ms
yncx:delay:start { wait: 200, label: 'test:somethingElse' } +0ms
yncx:delay:end { wait: 100, label: 'doSomeAsyncTask' } +0ms
yncx:doSomeAsyncTask Throwing error +0ms
yncx:testMiddleware Caught error +0ms
yncx:delay:end { wait: 200, label: 'test:somethingElse' } +0ms
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment