Skip to content

Commit

Permalink
Server: Improved logging and rendering of low level middleware errors
Browse files Browse the repository at this point in the history
  • Loading branch information
laurent22 committed Nov 1, 2021
1 parent c491741 commit 3704413
Showing 1 changed file with 23 additions and 11 deletions.
34 changes: 23 additions & 11 deletions packages/server/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import apiVersionHandler from './middleware/apiVersionHandler';
import clickJackingHandler from './middleware/clickJackingHandler';
import newModelFactory from './models/factory';
import setupCommands from './utils/setupCommands';
import { RouteResponseFormat, routeResponseFormat } from './utils/routeUtils';

interface Argv {
env?: Env;
Expand Down Expand Up @@ -139,17 +140,28 @@ async function main() {
} catch (error) {
ctx.status = error.httpCode || 500;

// Since this is a low level error, rendering a view might fail too,
// so catch this and default to rendering JSON.
try {
ctx.body = await ctx.joplin.services.mustache.renderView({
name: 'error',
title: 'Error',
path: 'index/error',
content: { error },
});
} catch (anotherError) {
ctx.body = { error: anotherError.message };
appLogger().error(`Middleware error on ${ctx.path}:`, error);

const responseFormat = routeResponseFormat(ctx);

if (responseFormat === RouteResponseFormat.Html) {
// Since this is a low level error, rendering a view might fail too,
// so catch this and default to rendering JSON.
try {
ctx.response.set('Content-Type', 'text/html');
ctx.body = await ctx.joplin.services.mustache.renderView({
name: 'error',
title: 'Error',
path: 'index/error',
content: { error },
});
} catch (anotherError) {
ctx.response.set('Content-Type', 'application/json');
ctx.body = JSON.stringify({ error: error.message });
}
} else {
ctx.response.set('Content-Type', 'application/json');
ctx.body = JSON.stringify({ error: error.message });
}
}
});
Expand Down

0 comments on commit 3704413

Please sign in to comment.