All files / app/errors error-handler.ts

83.33% Statements 25/30
70% Branches 7/10
100% Functions 1/1
83.33% Lines 25/30

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 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67  1x 1x 1x 1x 1x 1x 1x       1x 1x                 1x   148x 146x 146x         146x           2x       2x     2x   2x 1x 1x   1x 1x           2x           148x     1x  
import {ErrorRequestHandler} from 'express';
import RestError from './rest-error';
import InternalError from './internal-error';
import config from '@config';
import debug from 'debug';
import UnauthorizedRestError from './unauthorized-error';
import ForbiddenError from './forbidden-error';
import BadRequestError from './bad-request-error';
 
import {UnauthorizedError} from 'express-jwt';
 
const log = debug('group-car:error-handler');
const error = debug('group-car:error-handler:error');
 
/**
 * The general error handler for errors.
 * @param err - Thrown error
 * @param req - Request
 * @param res - Response
 */
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const errorHandler: ErrorRequestHandler = (err, _req, res, _next) => {
  let restError: RestError;
  if (err instanceof RestError) {
    log('Handling error: "%s"', err.constructor.name);
    restError = new RestError(
        err.statusCode,
        err.message,
        err.detail,
    );
    restError.detail = {
      ...restError.detail,
      errorName: err.constructor.name,
    };
  } else {
    // Check if authorization error
    Iif (err.name === 'UnauthorizedError') {
      log('Request with invalid jwt token handled. Message: %s',
          (err as UnauthorizedError).message);
      restError = new UnauthorizedRestError('Invalid token');
    } else Iif (err.code === 'EBADCSRFTOKEN') {
      log('Request has invalid csrf token');
      restError = new ForbiddenError();
    } else Iif (err instanceof SyntaxError) {
      restError = new BadRequestError('Malformed request');
    } else if (!config.error.withStack) {
      error(err.stack);
      restError = new InternalError();
    } else {
      error(err.stack);
      restError = new InternalError(
          err.message,
          undefined,
          err.stack,
      );
    }
    restError.detail = {
      ...restError.detail,
      errorName: restError.constructor.name,
    };
  }
 
  res.status(restError.statusCode).send(restError);
};
 
export default errorHandler;