# All files / server-old/plugins/final index.js

100% Statements 18/18
100% Branches 15/15
100% Functions 2/2
100% Lines 17/17

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45

    26x

    26x
    102x

    10x

    10x
    4x

    26x
    4x
    4x
    4x
    4x
    3x
    3x

    3x
    1x

    2x

    26x

     // This file makes sure to clean up things in case there was something missing
    // There are two reasons normally for this to happen: no reply was set or an
    // unhandled error was thrown
    const FinalError = require('./errors');

    // Make sure that a (404) reply is sent if there was no user reply
    const handler = async ctx => {
      if (!ctx.res.headersSent) {
        // Send the user-set status
        ctx.res.status(ctx.res.explicitStatus ? ctx.res.statusCode : 404).send();

        // Show it only if there was no status set in a return
        if (!ctx.res.explicitStatus) {
          ctx.log.error(
            new FinalError('noreturn', { url: ctx.url, method: ctx.method })
          );
        }
      }
    };

    // Make sure there is a (500) reply if there was an unhandled error thrown
    handler.error = ctx => {
      const error = ctx.error;
      ctx.log.warning(FinalError('unhandled'));
      ctx.log.error(error);
      if (!ctx.res.headersSent) {
        let status = error.status || error.code || 500;
        if (typeof status !== 'number') status = 500;

        // Display the error message if this error is marked as public
        if (error.public) {
          return ctx.res.status(status).send(error.message);
        }

        // Otherwise just display the default error for that code
        ctx.res.sendStatus(status);
      }
    };

    module.exports = {
      name: 'final',
      after: handler
    };
    // module.exports = handler;