Middleware & Filters — Series 3

Preview — 3 of 10 questions

Which exceptions belong in each position?

javascript
if (!token) throw new ???;              // no credentials at all
if (!user.roles.includes('admin')) throw new ???;   // authenticated but not allowed
AForbiddenException then UnauthorizedException
BUnauthorizedException in both cases, since both are access failures
CUnauthorizedException (401) when the caller has not proved who they are — retrying with credentials may succeed — and ForbiddenException (403) when the caller is known but not permitted, where retrying will not help
DBadRequestException then ForbiddenException

What does using the enum give over a numeric literal?

javascript
throw new HttpException('Teapot', HttpStatus.I_AM_A_TEAPOT);
res.status(HttpStatus.NO_CONTENT);
AA named, typed constant — HttpStatus.NO_CONTENT reads better than 204, the compiler catches a typo, and a search finds every use of a given status
BIt validates at runtime that the status is allowed for the current verb
CIt automatically sets the matching response body
DIt is required; numeric literals are rejected by HttpException

The class is written and exported, but responses keep the default shape. What is missing?

javascript
@Catch(NotFoundException)
export class NotFoundFilter implements ExceptionFilter {
  catch(exception: NotFoundException, host: ArgumentsHost) { /* ... */ }
}
AThe @Injectable() decorator
BAn @Catch() argument listing every exception subclass explicitly
CRegistration of the class with providers
DA binding: @Catch() only declares which exceptions the filter handles, never where it applies — it has to be attached with @UseFilters() on a handler or controller, app.useGlobalFilters(), or an APP_FILTER provider

Sign up free to play

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