Skip to content

Instantly share code, notes, and snippets.

@chimmelb
Created June 30, 2020 16:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chimmelb/23bbbb03a77f09f3683a96fd0c6cbdb0 to your computer and use it in GitHub Desktop.
Save chimmelb/23bbbb03a77f09f3683a96fd0c6cbdb0 to your computer and use it in GitHub Desktop.
Error Handling Pattern for actionheroJS
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>
}
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
}
}
/*
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