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
@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.
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:
server-error.ts (ErrorType is an enum)
Controller usage: