Vahid Najafi
Vahid Najafi

Reputation: 5253

Nestjs catch 500 error and return the error

When an unhandled error occurs, the front side gets a 500 error without any information about the error. It just receives this:

{
  "statusCode": 500,
  "message": "Internal server error"
}

But when I check the console, I see what happened and what the error message is. It's ok in the development environment but it's hard to figure out in production. How can I return a complete error message in production instead of just a simple message like "Internal server error"?

Upvotes: 11

Views: 29372

Answers (5)

1_1
1_1

Reputation: 1

Try to call Logger.error() at 1 line controller, if still return 500, check request interface, in my case that was a reason

@Post('register');
register(@Body() user: UserInterface): any { // UserInterface call 500 exception
  Logger.error('user', user)

Upvotes: 0

樱花庄的白猫H.
樱花庄的白猫H.

Reputation: 31

//InternalServerError.filter.ts
import {
    InternalServerErrorException,
    Catch,
    ArgumentsHost,
    ExceptionFilter,
    HttpStatus,
    HttpException
} from "@nestjs/common";
// catch all error
@Catch()
export default class InternalServerErrorExceptionFilter implements ExceptionFilter {
    catch(exception: Error, host: ArgumentsHost) {
      
        let { message: errMsg, stack: errStack, name: errName } = exception;
        // let errRes = exception.getResponse();
        // let errCode = exception.getStatus();
        let ctx = host.switchToHttp();
        let req = ctx.getRequest();
        let res = ctx.getResponse();
        const statusName = "系统内部错误";
        res.statusCode = HttpStatus.INTERNAL_SERVER_ERROR;
        // HttpException Error
        if (exception instanceof HttpException) {
            // set httpException res to res
            res.status(exception.getStatus()).json(exception.getResponse());
            return;
        }
        // other error to rewirte InternalServerErrorException response
        res.render("Error.ejs", {
            exception,
            errMsg,
            errStack,
            errName,
            statusCode: res.statusCode,
            statusName,
            req
        });
    }
}

then use global filter provider for InternalServerError.filter.ts

// app.module.ts
@Module({
providers:[{
        provide: APP_FILTER,
        useClass: InternalServerErrorExceptionFilter
    }])

Upvotes: 3

Janac Meena
Janac Meena

Reputation: 3567

Finally found the answer to this question - you don't need any complicated exception filters, or interceptors, etc. You just need to wrap the code which is causing the 500 in an if statement, and throw a HttpException - note, throwing an Error will not work.

In other words, you need to resolve this error in your service class, not in your controller.

For example, in your service class:

  async getUsers(){
    let response = doSomething();
    if (response.status !== 200) {
      throw new HttpException(
        `Error getting users: ${response.status} ${response.statusText}`,
        response.status,
      )
    } else {
      return response.data
    }
  }

Upvotes: 3

Daniel
Daniel

Reputation: 15413

NestJS has the NotFoundException you can use.

You can implement your own custom Exception filters and add it to your controllers to capture a NotFoundException or whatever communication protocol, but this is assuming that you have an HTTP communication protocol.

So if http is the only communication protocol you are dealing with then you can just write this into one of your methods inside your service:

if (!user) {
  throw new NotFoundException('user not found');
}

And you would import that from:

import { Injectable, NotFoundException } from '@nestjs/common';

Upvotes: 3

Jay McDoniel
Jay McDoniel

Reputation: 70171

Generally you should be doing error handling around things that have a chance to go wrong (database operations, sending emails, validations), but if you're looking for a general error handling mechanism, you can use the Exception Filters construct that Nest provides to catch errors and manage them as necessary.

Upvotes: 6

Related Questions