예외 처리는 서버의 안정성을 유지하고, 사용자에게 의미 있는 오류 메시지를 제공하기 위해 필수적이다.
import { Injectable, BadRequestException } from '@nestjs/common';
@Injectable()
export class ExampleService {
async performOperation(): Promise<string> {
try {
// 오류 발생 가능 코드
const result = await this.someAsyncTask();
return result;
} catch (error) {
throw new BadRequestException('Operation failed');
}
}
private async someAsyncTask(): Promise<string> {
throw new Error('Simulated error');
}
}
import { NotFoundException } from '@nestjs/common';
@Injectable()
export class UserService {
getUserById(id: number): any {
try {
const user = this.users.find((user) => user.id === id);
if (!user) throw new NotFoundException('User not found');
return user;
} catch (error) {
throw error;
}
}
}
async function fetchData() {
try {
const response = await axios.get('https://api.example.com');
return response.data;
} catch (error) {
throw new Error('Failed to fetch data');
}
}
import { Catch, ExceptionFilter, ArgumentsHost, HttpException } from '@nestjs/common';
@Catch(HttpException)
export class GlobalExceptionFilter implements ExceptionFilter {
catch(exception: HttpException, host: ArgumentsHost) {
const response = host.switchToHttp().getResponse();
response.status(exception.getStatus()).json({ message: exception.message });
}
}
async function getUser(id: number) {
try {
const user = await this.userRepository.findOneBy({ id });
if (!user) throw new NotFoundException('User not found');
return user;
} catch (error) {
throw new Error('Database error');
}
}