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
Was this helpful?