Created
June 30, 2020 16:19
-
-
Save chimmelb/23bbbb03a77f09f3683a96fd0c6cbdb0 to your computer and use it in GitHub Desktop.
Error Handling Pattern for actionheroJS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Action, ActionProcessor, log } from 'actionhero' | |
import { SmartError } from './SmartError' | |
export abstract class QuantumAction extends Action { | |
constructor() { | |
// extends Abstract class Action only to wrap | |
super() | |
} | |
async run(data: ActionProcessor): Promise<void> { | |
try { | |
await this.qRun(data) | |
} catch (error) { | |
let msg | |
/* | |
Any special error handling here, like catching different types of errors | |
or setting HTTP codes on web requests | |
*/ | |
if (error instanceof SmartError) { | |
msg = error.message | |
} else { | |
log('This error will be masked: ' + error.message, 'error') | |
log(error.stack, 'error') | |
msg = `Unexpected Internal Error. Request id: ${data.connection.fingerprint}` | |
} | |
// thrown errpr here is handled by normal actionhero action processing | |
throw new Error(msg) | |
} | |
} | |
/** | |
* | |
* @param data The data object of | |
*/ | |
abstract async qRun(data: ActionProcessor): Promise<void> | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export class SmartError extends Error { | |
constructor(message?: string) { | |
super(message) // 'Error' breaks prototype chain here | |
this.name = 'SmartError' | |
Object.setPrototypeOf(this, new.target.prototype) // restore prototype chain | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
An example action using the QuantumAction pattern that always breaks, but in different ways for unit tests. | |
*/ | |
import { chatRoom, Action } from 'actionhero' | |
import { SmartError } from '../path/to/SmartError' | |
import { QuantumAction } from '../path/to/QuantumAction' | |
export class WillBreak extends QuantumAction { | |
constructor() { | |
super() | |
this.name = 'willBreak' | |
this.description = 'I will always break' | |
this.inputs = { | |
dumb: { | |
required: false, | |
default: false, | |
}, | |
} | |
} | |
async qRun({ params, response }) { | |
if (params.dumb) throw new Error('dumb error!') | |
throw new SmartError('this is smart???') | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment