Skip to content

Commit

Permalink
feat: add custom errors
Browse files Browse the repository at this point in the history
  • Loading branch information
joachimvh committed Jun 5, 2020
1 parent cc8f965 commit 57405f3
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 0 deletions.
19 changes: 19 additions & 0 deletions src/util/errors/HttpError.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
/**
* An abstract class for all errors that could be thrown by Solid.
* All errors inheriting from this should fix the status code thereby hiding the HTTP internals from other components.
*/
export abstract class HttpError extends Error {
public statusCode: number;

/**
* Creates a new HTTP error. Subclasses should call this with their fixed status code.
* @param statusCode - HTTP status code needed for the HTTP response.
* @param name - Error name. Useful for logging and stack tracing.
* @param message - Message to be thrown.
*/
protected constructor (statusCode: number, name: string, message: string) {
super(message);
this.statusCode = statusCode;
this.name = name;
}
}
15 changes: 15 additions & 0 deletions src/util/errors/UnsupportedHttpError.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { HttpError } from './HttpError';

/**
* An error thrown when incoming data is not supported.
* Probably because an {@link AsyncHandler} returns false on the canHandle call.
*/
export class UnsupportedHttpError extends HttpError {
/**
* Default message is 'The given input is not supported by the server configuration.'.
* @param message - Optional, more specific, message.
*/
public constructor (message?: string) {
super(400, 'UnsupportedHttpError', message || 'The given input is not supported by the server configuration.');
}
}
17 changes: 17 additions & 0 deletions test/unit/util/errors/UnsupportedHttpError.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { UnsupportedHttpError } from '../../../../src/util/errors/UnsupportedHttpError';

describe('An UnsupportedHttpError', (): void => {
it('has status code 400.', async (): Promise<void> => {
const error = new UnsupportedHttpError('test');

expect(error.statusCode).toEqual(400);
expect(error.message).toEqual('test');
expect(error.name).toEqual('UnsupportedHttpError');
});

it('has a default message if none was provided.', async (): Promise<void> => {
const error = new UnsupportedHttpError();

expect(error.message).toEqual('The given input is not supported by the server configuration.');
});
});

0 comments on commit 57405f3

Please sign in to comment.