Skip to content

Throwing Http Errors from middleware #248

@mogusbi

Description

@mogusbi

Is it possible to throw http errors listed here with middleware and custom decorators?

Here's an example of what I'm trying to do;

// Unauthorised.ts

import {NextFunction, Request, Response} from 'express'
import {ForbiddenError, getMetadataArgsStorage} from 'routing-controllers';

export function Unauthorised (): Function {
  return (objectOrFunction: Object | Function, methodName?: string) => {
    getMetadataArgsStorage()
      .uses
      .push({
        afterAction: false,
        method: methodName,
        middleware: (req: Request, _: Response, next: NextFunction) => {
          if (req.headers.authorization) {
            throw new ForbiddenError();
          }

          next();
        },
        target: methodName ? objectOrFunction.constructor : objectOrFunction as Function
      });
  };
}

// auth.controller.ts

import {Body, JsonController, Post} from 'routing-controllers';
import {Unauthorised} from './Unauthorised';

@JsonController('/auth')
export class AuthController {
  @Post()
  @Unauthorised()
  public httpPost (
    @Body({
      required: true
    }) props
  ) {
    // do auth logic here if you're not already authorised
  }
}

But rather than returning the error response that it does when it's inside the controller, it literally throws the error and returns a 500 server error

POST /api/1.0/auth 500 11.622 ms - 2343
Error
    at ForbiddenError.HttpError [as constructor] (/HttpError.ts:19:22)
    at new ForbiddenError (/ForbiddenError.ts:10:9)
    at middleware (/Unauthorised.ts:12:19)

Metadata

Metadata

Assignees

No one assigned

    Labels

    type: questionQuestions about the usage of the library.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions