Skip to content

Instantly share code, notes, and snippets.

@garcia556
Created November 19, 2017 03:15
Show Gist options
  • Save garcia556/a2883cf9176b0bb93227354ebf0c33e9 to your computer and use it in GitHub Desktop.
Save garcia556/a2883cf9176b0bb93227354ebf0c33e9 to your computer and use it in GitHub Desktop.
Shows differences in koa error handling (for koa #1098)
'use strict';
const
PORT = 8080,
URL_LISTEN = `http://localhost:${PORT}`,
ROUTE_DEFAULT = "/default",
ROUTE_CUSTOM = "/custom",
ROUTE_CUSTOM_CODE = "/custom_code";
const
request = require("request"),
Koa = require("koa"),
app = new Koa(),
route = require("koa-route"),
rp = require("request-promise");
//////////////////////////////////////////////
const
CODE = 400,
MSG = "this is bad";
///////////////////////
const handlerDefault = (ctx) => {
ctx.assert(false, CODE, MSG);
};
const handlerCustom = (ctx) => {
try
{
ctx.assert(false, CODE, MSG);
}
catch (err)
{
console.log(`Hit custom error handler, err.status: ${err.status}`);
}
};
const handlerCustomCode = (ctx) => {
try
{
ctx.assert(false, CODE, MSG);
}
catch (err)
{
ctx.status = err.status || 500;
console.log(`Hit custom error handler, ctx.status set to err.status: ${ctx.status}`);
}
};
///////////////////////
app.use(route.get(ROUTE_DEFAULT , handlerDefault));
app.use(route.get(ROUTE_CUSTOM , handlerCustom));
app.use(route.get(ROUTE_CUSTOM_CODE, handlerCustomCode));
app.listen(PORT);
///////////////////////
async function req(url)
{
try { await rp(url); }
catch (err)
{
console.error(`Request failed with HTTP response code ${err.statusCode}\n`);
}
}
async function main()
{
await req(`${URL_LISTEN}${ROUTE_DEFAULT}`);
await req(`${URL_LISTEN}${ROUTE_CUSTOM}`);
await req(`${URL_LISTEN}${ROUTE_CUSTOM_CODE}`);
process.exit(0);
}
main().then().catch(console.error);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment