Search…
Problem

Nest Problem Module

This library includes a Nest Module that implements the Problem Details for HTTP APIs spec.

Usage

Import ProblemModule in your root NestJS module.
1
import { Module } from '@nestjs/common'
2
import { ProblemModule } from '@island.is/nest/problem'
3
4
@Module({
5
imports: [ProblemModule],
6
})
7
export class AppModule {}
Copied!
It will automatically filter all thrown errors and convert them to Problem Responses.

GraphQL

For unhandled errors thrown in a GraphQL context, this module will enrich them with a "problem" extension.
If the error already has a problem attribute, then that will be used.
Our Enhanced Fetch client automatically parses problem responses and includes a problem attribute in thrown errors. This means that problems from our REST services are automatically forwarded to the UI.
For expected problems, consider following GraphQL best practices and model them in the GraphQL schema.

Manual problem responses

The easiest way to manually return a problem response is to throw ProblemError or one of its subclasses like this:
1
import { ProblemError } from '@island.is/nest/problem'
2
import { ProblemType } from '@island.is/shared/problem'
3
4
throw new ProblemError({
5
type: ProblemType.HTTP_NOT_FOUND,
6
title: 'Not found',
7
})
Copied!
The following sub-classes are available for your convenience:
  • new ValidationFailed(fields) - accepts a record of validation issues.

Custom problems

If none of the existing problem types suits your needs, consider creating a new one.
When you've defined the problem type, you can return it like this:
1
import { ProblemError } from '@island.is/nest/problem'
2
import { ProblemType } from '@island.is/shared/problem'
3
4
throw new ProblemError({
5
type: ProblemType.NEW_PROBLEM,
6
title: 'Some new problem occurred',
7
extraAttribute: 'example',
8
})
Copied!
Optionally, you can create a ProblemError subclass like this:
1
import { ProblemType } from '@island.is/shared/problem'
2
import { ProblemError } from './ProblemError'
3
4
export class NewProblem extends ProblemError {
5
constructor(extraAttribute: string) {
6
super({
7
type: ProblemType.NEW_PROBLEM,
8
title: 'Some new problem',
9
status: 400,
10
extraAttribute,
11
})
12
}
13
}
14
15
// Later:
16
throw new NewProblem('extra')
Copied!

Running unit tests

Run nx test nest-problem to execute the unit tests via Jest.
Last modified 8d ago