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:
… 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:
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:
领英推荐
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