@nestjs/microservices
Version:
Nest - modern, fast, powerful node.js web framework (@microservices)
42 lines (41 loc) • 1.72 kB
JavaScript
import { of } from 'rxjs';
import { BaseRpcExceptionFilter } from './base-rpc-exception-filter.js';
import { RpcException } from './rpc-exception.js';
import { selectExceptionFilterMetadata, isEmptyArray, isUndefined, } from '@nestjs/common/internal';
import { InvalidExceptionFilterException } from '@nestjs/core/internal';
/**
* @publicApi
*/
export class RpcExceptionsHandler extends BaseRpcExceptionFilter {
filters = [];
/**
* @param reportUnhandled Log an `RpcException` no filter matched. An event
* handler has no response stream to carry it back, so it would be lost.
*/
handle(exception, host, reportUnhandled = false) {
const filterResult$ = this.invokeCustomFilters(exception, host);
// `undefined` stands for "not handled": no filter caught the exception,
// or the one that did returned nothing. Any other falsy result is still
// the response, wrapped as RxJS accepts only streams from `catchError()`.
if (!isUndefined(filterResult$)) {
return filterResult$ || of(filterResult$);
}
if (reportUnhandled && exception instanceof RpcException) {
BaseRpcExceptionFilter.logger.error(exception);
}
return super.catch(exception, host);
}
setCustomFilters(filters) {
if (!Array.isArray(filters)) {
throw new InvalidExceptionFilterException();
}
this.filters = filters;
}
invokeCustomFilters(exception, host) {
if (isEmptyArray(this.filters)) {
return;
}
const filter = selectExceptionFilterMetadata(this.filters, exception);
return filter ? filter.func(exception, host) : undefined;
}
}