"use strict";

module.exports = {

	initErrors() {

		if (!this.hasInitiatedErrors) {

			let originalExHandlers = this.addListenerFirst(process, 'uncaughtException', err => {
				err.originalExHandlers = originalExHandlers;
				this.complete(err);
			}, true);
			this.hasInitiatedErrors = true;
		}
	},

	/**
  * Our error handler to call for any public API errors caused by a consumer's use of the API
  * This handler will produce an error to be sent as JSON over the API rather than an exception.
  * 
  * ------------ WARNING ------------
  * When using this function, please ensure no other code will run afterwards within the callback
  * ---------------------------------
  * 
  * @param  {string} message    A short message describing the error
  * @param  {Number} statusCode HTTP status code
  * @param  {string} item       A string representing the field causing the issue
  */
	error(message, statusCode, item) {

		if (this.isAPI) {

			if (!statusCode) {
				statusCode = 400;
			}
			if (!item) {
				item = null;
			}

			let error = {
				message: message,
				statusCode: statusCode
			};

			if (item) {
				error.item = item;
			}

			this.response.setStatus(statusCode);
			this.response.setBody(this.serializer.error(error));
			this.complete();

			var err = new Error('Blackout API Error');

			// Prevent error being thrown so we can handle gracefully
			try {
				// Error is handled by API and presented to API user
				// Let our error handler know we don't need to do anything else
				throw err;
			} catch (err) {
				// Don't do anything since this is already handled via API output
				if (blackoutLocalMode) {
					console.log(error);

					// Don't just exit
					// .complete() may be cleaning up client locks and needs to wait
					// The autocompleter will wrap up
					//process.exit(); 
				}
			}
		} else {
			this.complete(new Error('Please use errorInternal() for non-consumer API errors. Original error message: ' + message));
		}
	},

	/**
  * Call this for any internal errors not caused by a client using the API (in which case you would use error())
  * 
  * Preferably should send an error object so that the stack trace is generated at the source of the error, but strings are accepted
  * @param  {[type]} err [description]
  * @return {[type]}     [description]
  */
	errorInternal(err) {

		this.complete(err);
	}

};
//# sourceMappingURL=errors.js.map