Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions docs/site/Advanced-sequence-topics.md
Original file line number Diff line number Diff line change
Expand Up @@ -282,6 +282,35 @@ details.
}
```

### Using the built-in error code mapping

A custom `reject` action can use the `mapErrorCodeToStatusCode` helper from
`@loopback/rest` to reuse the default mapping when choosing an HTTP status code:

```ts
import {Provider} from '@loopback/core';
import {mapErrorCodeToStatusCode, Reject, RestBindings} from '@loopback/rest';

export class CustomRejectProvider implements Provider<Reject> {
value(): Reject {
return ({response}, error) => {
const err = error as Error & {
code?: string;
status?: number;
statusCode?: number;
};
if (!err.status && !err.statusCode && err.code) {
err.statusCode = mapErrorCodeToStatusCode(err.code);
}
response.statusCode = err.statusCode || err.status || 500;
response.end();
};
}
}

app.bind(RestBindings.SequenceActions.REJECT).toProvider(CustomRejectProvider);
```

During development and testing, it may be useful to see all error details in the
HTTP response returned by the server. This behavior can be enabled by enabling
the `debug` flag in error-handler configuration as shown in the code example
Expand Down
40 changes: 39 additions & 1 deletion packages/rest/src/__tests__/unit/router/reject.provider.unit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,30 @@ import {
SinonSpy,
stubExpressContext,
} from '@loopback/testlab';
import {LogError, RejectProvider} from '../../..';
import {
LogError,
mapErrorCodeToStatusCode,
Reject,
RejectProvider,
} from '../../..';

describe('mapErrorCodeToStatusCode', () => {
it('maps ENTITY_NOT_FOUND to status code 404', () => {
expect(mapErrorCodeToStatusCode('ENTITY_NOT_FOUND')).to.equal(404);
});

it('returns undefined for an unknown code', () => {
expect(mapErrorCodeToStatusCode('UNKNOWN_CODE')).to.equal(undefined);
});

it('returns undefined when no code is provided', () => {
expect(mapErrorCodeToStatusCode()).to.equal(undefined);
});

it('does not map inherited object properties', () => {
expect(mapErrorCodeToStatusCode('constructor')).to.equal(undefined);
});
});

describe('reject', () => {
const noopLogger: LogError = () => {};
Expand Down Expand Up @@ -40,6 +63,21 @@ describe('reject', () => {
expect(result.statusCode).to.equal(404);
});

it('allows a custom reject to map an error code', async () => {
const reject: Reject = ({response}, error) => {
const err = error as Error & {code?: string};
response.statusCode = mapErrorCodeToStatusCode(err.code) ?? 500;
response.end();
};
const notFoundError: Error & {code?: string} = new Error('not found');
notFoundError.code = 'ENTITY_NOT_FOUND';

reject(contextStub, notFoundError);
const result = await contextStub.result;

expect(result.statusCode).to.equal(404);
});

it('logs the error', async () => {
const logger = sinon.spy() as LogError & SinonSpy;
const reject = RejectProvider.value(logger);
Expand Down
15 changes: 14 additions & 1 deletion packages/rest/src/providers/reject.provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,19 @@ const codeToStatusCodeMap: {[key: string]: number} = {
ENTITY_NOT_FOUND: 404,
};

/**
* Map an error code to an HTTP status code.
*
* @param code - The error code to map.
* @returns The matching status code, or `undefined` if the code is not mapped.
*/
export function mapErrorCodeToStatusCode(code?: string): number | undefined {
if (code && Object.prototype.hasOwnProperty.call(codeToStatusCodeMap, code)) {
return codeToStatusCodeMap[code];
}
return undefined;
}

@injectable({scope: BindingScope.SINGLETON})
export class RejectProvider {
static value(
Expand All @@ -27,7 +40,7 @@ export class RejectProvider {
const err = <HttpError>error;

if (!err.status && !err.statusCode && err.code) {
const customStatus = codeToStatusCodeMap[err.code];
const customStatus = mapErrorCodeToStatusCode(err.code);
if (customStatus) {
err.statusCode = customStatus;
}
Expand Down