Skip to content

Instantly share code, notes, and snippets.

@desaiuditd
Created September 16, 2019 01:21
Show Gist options
  • Save desaiuditd/396b00ffb7ed9b654bd6d4449174019a to your computer and use it in GitHub Desktop.
Save desaiuditd/396b00ffb7ed9b654bd6d4449174019a to your computer and use it in GitHub Desktop.
Custom Error class in JS
import myErrorCodes from './error-codes';
import MyError from './error';
const main = () => {
const success = false;
// add some business logic here.
if ( success === false ) {
new MyError(errorCodes.page_not_found);
}
};
main();
export default {
JOHN: {
code: 'JOHN',
status: 500,
message: 'Unregistered error',
source: 'core'
},
page_not_found: {
code: 'page_not_found',
status: 404,
message: 'Page is not found.',
source: 'core'
},
object_not_found: {
code: 'object_not_found',
status: 404,
message: 'Object is not found.',
source: 'core'
},
collection_not_found: {
code: 'collection_not_found',
status: 404,
message: 'Collection is not found.',
source: 'core'
},
unauthorized_access: {
code: 'unauthorized_access',
status: 401,
message: 'You are not authorized to access this resource.',
source: 'core'
},
forbidden_access: {
code: 'forbidden_access',
status: 403,
message: 'You are forbidden to access this resource.',
source: 'core'
}
};
import myErrorCodes from './error-codes';
type errorJSON = {|
message: string,
code: string,
status: number,
source: string,
details?: {}
|};
export default class MyError extends Error {
code: string
status: number
source: string
details: {}
constructor(error: errorJSON = ftErrorCodes.JOHN, details: {} = {}) {
super(error.message);
this.message = error.message;
this.code = error.code;
this.status = error.status;
this.source = error.source;
this.details = details;
}
toString(): string {
return JSON.stringify(this.toJSON(), null, '\t');
}
toJSON(): { errors: errorJSON } {
const curErr = {
message: this.message,
code: this.code,
status: this.status,
source: this.source,
details: this.details,
};
return {
errors: curErr,
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment