Tsoa: Error handling - How to return status code and custom error message

Created on 9 Aug 2017  路  6Comments  路  Source: lukeautry/tsoa

Hi @lukeautry ,

unfortunately i have no idea how i can handle my errors get from my backend systems, eg. DB.
I have a Promise which rejects with an error message when an error occurs:

Service:
return service.user.getUserInfo(id);

Controller:

getUserInfo(id: string): Promise<UserObject> {

        let result = new Promise<UserObject>((resolve, reject) => {
            let query = dbConnection.getUser(id); //Returns a Promise
            query.catch((err) => {
                reject(new Error("user not found"));
            }).then((response) => {
                resolve(response);
            });
        });
        return result;
    }

How can i manage to return a custom status code with an error?

Would be great if you can give me some ideas and advice ;)

question

Most helpful comment

ApiError.ts

export class ApiError extends Error {
    private statusCode: number;
    constructor(name: string, statusCode: number, message?: string) {
        super(message);
        this.name = name;
        this.statusCode = statusCode;
    }
}

If use promise

public async getUserInfo(id: string): Promise<UserObject> {
  return dbConnection.getUser(id)
           .then(res => {
              return res;
           })
           .catch(err => {
               throw new ApiError("UserNotFount",400,"user not found");
           });
}

If use Async/Await

public async getUserInfo(id: string): Promise<UserObject> {
  try {
      const res = awit condbConnection.getUser(id);
      return res;
  } catch (error) {
      throw new ApiError("UserNotFount",400,"user not found");
  }
}

express.js

import * as express from "express";
import * as errorHandler from "api-error-handler";

const app = express();
...
app.use(errorHandler());
app.listen(3000);

response

{
  "name": "UserNotFount",
   "status": 400,
  "message": "user not found"
}

All 6 comments

ApiError.ts

export class ApiError extends Error {
    private statusCode: number;
    constructor(name: string, statusCode: number, message?: string) {
        super(message);
        this.name = name;
        this.statusCode = statusCode;
    }
}

If use promise

public async getUserInfo(id: string): Promise<UserObject> {
  return dbConnection.getUser(id)
           .then(res => {
              return res;
           })
           .catch(err => {
               throw new ApiError("UserNotFount",400,"user not found");
           });
}

If use Async/Await

public async getUserInfo(id: string): Promise<UserObject> {
  try {
      const res = awit condbConnection.getUser(id);
      return res;
  } catch (error) {
      throw new ApiError("UserNotFount",400,"user not found");
  }
}

express.js

import * as express from "express";
import * as errorHandler from "api-error-handler";

const app = express();
...
app.use(errorHandler());
app.listen(3000);

response

{
  "name": "UserNotFount",
   "status": 400,
  "message": "user not found"
}

_How do you annotate that function so the error is included in the swagger config?_

In case anyone stumbles upon this question as well:
@Response<ErrorType>('statusCode', 'description')

e.g. @Response<MyErrorType>('403', 'forbidden')

Any suggestions on @Faberle's question?

@lukeautry Is it possible and if so, how do we instrument the tsoa code generator such that error codes & error descriptions are included into the generated swagger config?

Thx!

Hello,
For your case, do you use koa or express as a middleware ?
For me I'm using koa as a middleware, and i put this code and it's working fine for me to return a custom error response :

in my app.ts wich contain the main application server i put this :

    server.use(async (ctx, next) => {
      try {
        await next();
      } catch (err) {
        err.status = err.statusCode || err.status || 500;
        err.message = err.message;
        ctx.body = err.message;
      }
    });
    server.use(KoaBody());

and in the controller i put this :

   try {
      return await  asynchronousTreatment();
    } catch (error) {
      throw new ApiError(500, error.message);
    }

And i use the Api Error of @isman-usoh, that all

Looks like this is a solved problem.

Looks like this is a solved problem.

yep it's seems so :)

Was this page helpful?
0 / 5 - 0 ratings

Related issues

jakubzloczewski picture jakubzloczewski  路  6Comments

strongpauly picture strongpauly  路  3Comments

Izabrr picture Izabrr  路  4Comments

jeremyVignelles picture jeremyVignelles  路  3Comments

caringdeveloper picture caringdeveloper  路  3Comments