Tsoa: authenticationMiddleware return error as JSON directly

Created on 8 Oct 2018  路  3Comments  路  Source: lukeautry/tsoa

Hello,
is there any way to return a JSON object from the authenticationMiddleware to the caller without changing the template? In some cases I just want to return a plain JSON object to the client to tell the client the reason why the authentication failed and can not work with the generic 401 return.

Best regards

Most helpful comment

@Peekaboo1337 The pattern I use is to throw errors, and I have a special ServerError type with various properties.

Using express, I create this handler:

app.use((err: any, _req: express.Request, res: express.Response, next: express.NextFunction) => {
    const status = err.status || 500;
    const body: any = {
      fields: err.fields || undefined,
      message: err.message || 'An error occurred during the request.',
      name: err.name,
      status,
      type: err.type || ErrorType.Unknown
    };
    res.status(status).json(body);
    next();
  });

server-error.ts (ErrorType is an enum)

export class ServerError extends Error {
  constructor(
    message: string,
    public readonly status = 500,
    public readonly type: ErrorType = ErrorType.Unknown
  ) {
    super(message);
  }
}

Controller usage:

throw new ServerError('this is a message', HttpStatusCode.NotFound, ErrorType.MyCustomErrorType)

All 3 comments

@Peekaboo1337 The pattern I use is to throw errors, and I have a special ServerError type with various properties.

Using express, I create this handler:

app.use((err: any, _req: express.Request, res: express.Response, next: express.NextFunction) => {
    const status = err.status || 500;
    const body: any = {
      fields: err.fields || undefined,
      message: err.message || 'An error occurred during the request.',
      name: err.name,
      status,
      type: err.type || ErrorType.Unknown
    };
    res.status(status).json(body);
    next();
  });

server-error.ts (ErrorType is an enum)

export class ServerError extends Error {
  constructor(
    message: string,
    public readonly status = 500,
    public readonly type: ErrorType = ErrorType.Unknown
  ) {
    super(message);
  }
}

Controller usage:

throw new ServerError('this is a message', HttpStatusCode.NotFound, ErrorType.MyCustomErrorType)

@lukeautry This looks awesome. Thanks a lot! Will implement!

Just commenting to say this helped me out tremendously! This advice could probably be placed in the main documentation since a lot of developers probably want the functionality to pass back a custom error message.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

jeremyVignelles picture jeremyVignelles  路  3Comments

rdhelms picture rdhelms  路  4Comments

lonix1 picture lonix1  路  5Comments

jakubzloczewski picture jakubzloczewski  路  6Comments

ancizararenas picture ancizararenas  路  3Comments