Exception filters

Exception filters

HTTP ์˜ˆ์™ธ ํ•„ํ„ฐ ๊ณ„์ธต๊ณผ ํ•ด๋‹น ๋งˆ์ดํฌ๋กœ ์„œ๋น„์Šค ๊ณ„์ธต์˜ ์œ ์ผํ•œ ์ฐจ์ด์ ์€ HttpException์„ ๋ฐœ์ƒ์‹œํ‚ค๋Š” ๋Œ€์‹ RpcException์„ ์‚ฌ์šฉํ•ด์•ผ ํ•œ๋‹ค๋Š” ๊ฒƒ์ž…๋‹ˆ๋‹ค.

throw new RpcException('Invalid credentials.');

info ํžŒํŠธ RpcException ํด๋ž˜์Šค๋Š”@nestjs/microservices ํŒจํ‚ค์ง€์—์„œ ๊ฐ€์ ธ์˜ต๋‹ˆ๋‹ค.

Nest๋Š” ๋ฐœ์ƒ๋œ ์˜ˆ์™ธ๋ฅผ ์ฒ˜๋ฆฌํ•˜๊ณ  ๊ฒฐ๊ณผ์ ์œผ๋กœ ๋‹ค์Œ ๊ตฌ์กฐ์˜ error ๊ฐ์ฒด๋ฅผ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค.

{
  "status": "error",
  "message": "Invalid credentials."
}

Filters

์˜ˆ์™ธ ํ•„ํ„ฐ๋Š” ๊ธฐ๋ณธ ํ•„ํ„ฐ์™€ ๋™์ผํ•œ ๋ฐฉ์‹์œผ๋กœ ์ž‘๋™ํ•˜์ง€๋งŒ ์ž‘์€ ์ฐจ์ด๊ฐ€ ์žˆ์Šต๋‹ˆ๋‹ค. catch()๋ฉ”์†Œ๋“œ๋Š” Observable์„ ๋ฆฌํ„ดํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.

@@filename(rpc-exception.filter)
import { Catch, RpcExceptionFilter, ArgumentsHost } from '@nestjs/common';
import { Observable, throwError } from 'rxjs';
import { RpcException } from '@nestjs/microservices';

@Catch(RpcException)
export class ExceptionFilter implements RpcExceptionFilter<RpcException> {
  catch(exception: RpcException, host: ArgumentsHost): Observable<any> {
    return throwError(exception.getError());
  }
}

๊ฒฝ๊ณ  ํ•˜์ด๋ธŒ๋ฆฌ๋“œ ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜ ๊ธฐ๋Šฅ์„ ์‚ฌ์šฉ์ค‘์ธ ๊ฒฝ์šฐ ๋งˆ์ดํฌ๋กœ ์„œ๋น„์Šค ์˜ˆ์™ธ ํ•„ํ„ฐ๋ฅผ ์ „์ฒด์ ์œผ๋กœ ์„ค์ •ํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค.

๋‹ค์Œ์€ ์ˆ˜๋™์œผ๋กœ ์ธ์Šคํ„ด์Šคํ™” ๋œ ๋ฉ”์†Œ๋“œ ๋ฒ”์œ„ ํ•„ํ„ฐ๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ์˜ˆ์ž…๋‹ˆ๋‹ค (ํด๋ž˜์Šค ๋ฒ”์œ„๋„ ์ž‘๋™ ํ•จ).

@@filename()
@UseFilters(new ExceptionFilter())
@MessagePattern({ cmd: 'sum' })
accumulate(data: number[]): number {
  return (data || []).reduce((a, b) => a + b);
}

Inheritance

์ผ๋ฐ˜์ ์œผ๋กœ ์‘์šฉ ํ”„๋กœ๊ทธ๋žจ ์š”๊ตฌ ์‚ฌํ•ญ์„ ์ถฉ์กฑํ•˜๋„๋ก ์ œ์ž‘๋œ ์™„์ „ํžˆ ์‚ฌ์šฉ์ž ์ง€์ •๋œ ์˜ˆ์™ธ ํ•„ํ„ฐ๋ฅผ ๋งŒ๋“ญ๋‹ˆ๋‹ค. ์ด๋ฏธ ๊ตฌํ˜„ ๋œ ํ•ต์‹ฌ ์˜ˆ์™ธ ํ•„ํ„ฐ๋ฅผ ์žฌ์‚ฌ์šฉํ•˜๊ณ  ํŠน์ • ์š”์ธ์— ๋”ฐ๋ผ ๋™์ž‘์„ ์žฌ์ •์˜ํ•˜๋ ค๋Š” ๊ฒฝ์šฐ ์‚ฌ์šฉ ์‚ฌ๋ก€๊ฐ€ ์žˆ์„ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

์˜ˆ์™ธ ์ฒ˜๋ฆฌ๋ฅผ ๊ธฐ๋ณธ ํ•„ํ„ฐ์— ์œ„์ž„ํ•˜๋ ค๋ฉด BaseExceptionFilter๋ฅผ ํ™•์žฅํ•˜๊ณ  ์ƒ์† ๋œ catch() ๋ฉ”์†Œ๋“œ๋ฅผ ํ˜ธ์ถœํ•ด์•ผํ•ฉ๋‹ˆ๋‹ค. ๊ฒŒ๋‹ค๊ฐ€ HttpServer ์ฐธ์กฐ๊ฐ€ ์ฃผ์ž…๋˜์–ด super() ํ˜ธ์ถœ๋กœ ์ „๋‹ฌ๋˜์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.

@@filename()
import { Catch, ArgumentsHost } from '@nestjs/common';
import { BaseRpcExceptionFilter } from '@nestjs/microservices';

@Catch()
export class AllExceptionsFilter extends BaseRpcExceptionFilter {
  catch(exception: any, host: ArgumentsHost) {
    return super.catch(exception, host);
  }
}

๋ถ„๋ช…ํžˆ, ๋‹น์‹ ์€ ๋งž์ถคํ˜• ๋น„์ฆˆ๋‹ˆ์Šค ๋…ผ๋ฆฌ๋กœ ๋‹ค์–‘ํ•œ ๊ตฌํ˜„์„ ๊ฐ•ํ™”ํ•ด์•ผํ•ฉ๋‹ˆ๋‹ค (์˜ˆ: ๋‹ค์–‘ํ•œ ์กฐ๊ฑด ์ถ”๊ฐ€).

Last updated