Example: throw new Error('Boom');
All I get for response is the following:
{
"statusCode": 500,
"message": "Internal server error"
}
In express we have this
app.use(function (err, req, res, next) {
// logic
})
What about nest?
I read the docs, but it only catches http errors.
hey you can have a look on this : https://github.com/adrien2p/nest-js-sequelize-jwt/blob/master/src/modules/common/filters/DispatchError.ts
and documentation : https://docs.nestjs.com/exception-filters
I see, thanks.
Here is an example which catches any error, and renders templates for certain errors.
By the way, as of nest 5.0.0, the 2nd param for the catch method is an ArgumentsHost object, which encapsulates the response object.
# errors.filter.ts
import { ExceptionFilter, Catch, HttpException, ArgumentsHost, HttpStatus } from '@nestjs/common';
@Catch()
export class ErrorFilter implements ExceptionFilter {
catch(error: Error, host: ArgumentsHost) {
let response = host.switchToHttp().getResponse();
let status = (error instanceof HttpException) ? error.getStatus(): HttpStatus.INTERNAL_SERVER_ERROR;
if (status === HttpStatus.UNAUTHORIZED)
return response.status(status).render('views/401');
if (status === HttpStatus.NOT_FOUND)
return response.status(status).render('views/404');
if (status === HttpStatus.INTERNAL_SERVER_ERROR) {
if (process.env.NODE_ENV === 'production') {
console.error(error.stack);
return response.status(status).render('views/500');
}
else {
let message = error.stack;
return response.status(status).send(message);
}
}
}
}
# main.ts
import { NestFactory } from '@nestjs/core';
import { ApplicationModule } from './app.module';
import { ErrorFilter } from './app/errors/error.filter';
async function bootstrap() {
const app = await NestFactory.create(ApplicationModule);
app.useStaticAssets(__dirname + '/public');
app.setBaseViewsDir(__dirname + '/views');
app.setViewEngine('ejs');
app.useGlobalFilters(new ErrorFilter())
await app.listen(3000);
}
bootstrap();
This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.
Most helpful comment
Here is an example which catches any error, and renders templates for certain errors.
By the way, as of nest 5.0.0, the 2nd param for the catch method is an ArgumentsHost object, which encapsulates the response object.