Skip to content

Error response in JSON format #16

@mrslnv

Description

@mrslnv

UC: Implementing an async request.

  • while processing the request, an error condition occurs and it is necessary to inform client about the problem (preferably JSON)
  • when an error occurs in the service, there are 2 cases:
  1. rejecting the returned promise => content type is set to: text/html
  2. an exception is thrown => again, content type is set to: text/html

Desired behavior:

  • when an object is returned via reject(object), send back JSON (as for regular response)
  • when an exception is thrown, allow service to set content type and respond with JSON

Suggested workaround:
app.use((err: any, req: express.Request, res: express.Response, next: express.NextFunction) => {
if (err instanceof BadRequestError){
res.set("Content-Type", "application/json")
res.status(err.statusCode)
res.json({info : err.message, data: err.data});
} else {
next(err);
}
});

This works fine here:
@path("dummy1")
@get
dummy1(): Promise {
return new Promise(function (resolve, reject) {
throw new BadRequestError("Works fine, JSON is sent",{some:"data"});
});
}

But it does not work here:
@path("dummy2")
@get
dummy2(): Promise {
return new Promise(function (resolve, reject) {
setTimeout(()=>{
throw new BadRequestError("error handling not applied",{some:"data"});
},1000);
});
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions