Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Error handling - How to return status code and custom error message #150

Closed
eluft84 opened this issue Aug 9, 2017 · 7 comments
Closed
Labels

Comments

@eluft84
Copy link

eluft84 commented Aug 9, 2017

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 ;)

@isman-usoh
Copy link
Collaborator

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"
}

@Faberle
Copy link

Faberle commented Jun 25, 2018

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')

@danieldietrich
Copy link

danieldietrich commented Oct 17, 2018

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!

@hatim-heffoudhi
Copy link

hatim-heffoudhi commented May 22, 2019

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

@lukeautry
Copy link
Owner

Looks like this is a solved problem.

@hatim-heffoudhi
Copy link

hatim-heffoudhi commented Jun 19, 2019

Looks like this is a solved problem.

yep it's seems so :)

@douglasg14b
Copy link

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

Where is this coming from? What is inside of it?? This is the "draw the rest of the owl" moment for me :/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

7 participants