Filter Hierarchy — Series 2

Preview — 3 of 10 questions

What does listing two types achieve?

javascript
@Catch(NotFoundException, BadRequestException)
export class ClientErrorFilter implements ExceptionFilter {
  catch(exception: NotFoundException | BadRequestException, host: ArgumentsHost) { /* ... */ }
}
AThe filter runs twice, once per declared type
BOnly the first type is honoured; the rest are ignored
CThe filter matches instances of either class (and their subclasses), which is the idiomatic way to give a family of related errors one consistent response shape
DThe two types are intersected, so only an exception that is both is matched

What is the main argument for this filter over try/catch in each service?

javascript
@Catch(Prisma.PrismaClientKnownRequestError)
export class PrismaFilter implements ExceptionFilter {
  catch(exception: Prisma.PrismaClientKnownRequestError, host: ArgumentsHost) {
    const res = host.switchToHttp().getResponse();
    switch (exception.code) {
      case 'P2025': return res.status(404).json({ message: 'Record not found' });
      case 'P2002': return res.status(409).json({ message: 'Duplicate entry' });
      default: return res.status(500).json({ message: 'Database error' });
    }
  }
}
AIt is faster, because filters run outside the request pipeline
BIt is the only way to reach the response object from a service
CIt prevents the ORM from throwing in the first place
DThe translation from persistence errors to HTTP semantics lives in exactly one place, so every route gets consistent status codes without services having to know anything about HTTP

What can the exception filter do about this?

javascript
@Get('export')
async export(@Res() res: Response) {
  res.status(200);
  res.write('id,name\n');
  throw new InternalServerErrorException();   // mid-stream failure
}
AReset the response and send a clean 500 with a JSON body
BEssentially nothing useful: the status line and part of the body are already on the wire, so setting a new status is ignored (or throws ERR_HTTP_HEADERS_SENT) — the only sound options are to log the failure and destroy the connection so the client sees a truncated, failed transfer
CBuffer the remaining output and retry the handler
DConvert the response into a 206 Partial Content

Sign up free to play

Answer all 10 questions (7 more), see explanations for every answer, and track your score.