Let's Talk About Error Handling in NestJS! ??

Let's Talk About Error Handling in NestJS! ??

Alright, I know what you’re thinking – error handling isn’t exactly the topic we love talking about, right? But trust me, it’s way more important than we give it credit for. So let’s break it down without all the jargon and get into the stuff that really matters. ??

?? System Errors vs User Errors: What’s the Difference? When you’re building a NestJS app (or really any backend app), there are two main types of errors you’ll run into: system errors and user errors. Let’s take a closer look at each:

?? System Errors: These are the ones that happen because of something outside of your control – usually due to the environment your app is running in. Think of it like the app is saying, “Hey, I tried to do something, but the system said NOPE.”

Here are a few of the most common ones:

  • EACCES - Permission denied (did you forget to use sudo?)
  • EADDRINUSE - Address already in use (someone else is hogging your port!)
  • ENOENT - No such file or directory (you’re trying to access a file that doesn’t exist)
  • ECONNRESET - Connection reset by peer (basically, the network dropped you)

… and more! ?? Why should you care? Because if you don’t handle these errors right, your app could crash or behave unexpectedly. And that’s the last thing you want.

???? User Errors: These ones are on us – the users (or maybe even you as the developer). This happens when the user does something unexpected, like entering the wrong data or missing a required field.

For example, imagine you’re building a form and the user enters text where a number should be. It’s like saying, “Can I get a burger instead of a pizza?” ?? – not gonna work! ??????

?? How Do You Handle These Errors in NestJS? NestJS makes error handling pretty smooth with tools like:

  • Exception Filters: These catch and handle exceptions thrown in your app, ensuring you send a meaningful response to the client.
  • Guards: Use guards to protect routes and ensure users meet certain criteria before accessing them.
  • Interceptors: These can transform and log responses or handle errors globally.

For user errors, you can use class-validator and class-transformer to validate input data and avoid those “oops, I broke it” moments.

?? Quick Tips:

  • Log your errors! Trust me, when that error pops up in the middle of the night, you’ll be happy you logged it. ??
  • Use try-catch blocks to handle async errors and give the user a helpful message. No one likes unhandled promise rejections.


Code Examples


1. Handling Errors with Exception Filters

import { ExceptionFilter, Catch, ArgumentsHost, HttpException } from '@nestjs/common';
import { Response } from 'express';

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const status = exception.getStatus();

    response.status(status).json({
      statusCode: status,
      message: exception.message,
      timestamp: new Date().toISOString(),
    });
  }
}        


2. Validating User Input

import { IsString, IsInt, Min, Max } from 'class-validator';

export class CreateUserDto {
  @IsString()
  name: string;

  @IsInt()
  @Min(1)
  @Max(100)
  age: number;
}

// In your controller
@Post()
create(@Body() createUserDto: CreateUserDto) {
  return this.userService.create(createUserDto);
}        


3. Using Guards for Route Protection

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

@Injectable()
export class AuthGuard implements CanActivate {
  canActivate(context: ExecutionContext): boolean {
    const request = context.switchToHttp().getRequest();
    return request.headers.authorization === 'my-secret-token';
  }
}

// Applying the guard
@Get()
@UseGuards(AuthGuard)
findAll() {
  return this.userService.findAll();
}        


??♂? Wrapping Up: I get it – error handling isn't the most exciting thing to talk about, but trust me, it’ll save you a ton of headaches later on. By handling errors properly, your app stays stable and your users stay happy.

So, let’s all take a deep breath, embrace the errors, and build awesome NestJS apps that just work! ??

#NestJS #ErrorHandling #SystemErrors #UserErrors #DevLife #NodeJS #SoftwareEngineering #TechHumor

要查看或添加评论,请登录

Razmik Hovhannisyan的更多文章

社区洞察

其他会员也浏览了