CWCO logo

v1.7.5

Errors

In HTML, if something is invalid it will simply be ignored most of the time. If you provide invalid attribute value or fail to provide a required attributes, the DOM will simply ignore the element.

WebComponent follows the same philosophy. If you provide invalid attribute value or fail to provide a required attribute, it will simply be ignored. Anything that goes wrong with your component will be logged to the console but will not prevent the rest of the app from working unless it affects the internal logic.

CWCO is very forgiven until you do something that really upsets the internal logic of things.

onError

This livecycle function is called when an error occurs during the component rendering.

class ErrorExample extends WebComponent {
	onError(error) {
		alert(`error ${error.message}`)
	}
	
	onMount() {
		throw new Error('failed');
	}
	
	get template() {
		return `
			<button type="button" onclick="throwError()">
				throw error
			</button>`
	}
	
	throwError() {
		this.onError(new Error('throwError'))
	}
}

ErrorExample.register();

You may also call it directly as it is the only lifecycle method that you are allowed to call. When called it is passed the error object and by default it will simply log the error to the console.

Global error handler

onError is the perfect hook to use to debug your application since it can also be used to track errors globally.

You can simply create a static component which sole purpose is to handle errors.

const {WebComponent} = window;

class Component extends WebComponent {
	onError(error) {
		// call super.onError() to log the error to the console.
		super.onError(error);
		
		// here you can
		// - send error to some tracking analytics
		// - add error handling logic you need for your app.
	}
}

With such component, instead of using WebComponent to create your components, you can simply use Component so any error that occurs can be handled in a single place.

class HeadingTitle extends Component {
	static observedAttributes = ['text', 'type'];
	
	onMount() {
		// any error you throw or
		// the component throws will
		// be handled by Component
		throw new Error('failed');
	}
	
	get template() {
		return `<${this.type}><slot>{text}</slot></${this.type}>`
	}
}

HeadingTitle.register()

This is simply using the power of OOP inheritance to handle errors. CWCO has no specific say so on how you work. Simply take advantage of OOP to create things.