#loading

Error handling in swift

Error handling in swift

Jul 15, 2019

There are many ways to handle errors in Swift written applications, though sometimes errors of several various types may occur therein. The easiest way to fix them is to provide a single error handling function that receives an «Error» instance as a parameter and checks its pertinence to all possible error types. Although this is not the best solution since the application can produce errors of each type, your switch case will continually grow.

Bad solution example:

func handle(_ error: Error) {
	switch error {
	case is APIException:
		//handle api exception
	case is ValidationException:
		//handle validation exception
	//etc.
	}
}

There is a way to improve this massive code using separate methods to handle each type of exception, and calling them in each case of the handler described above. However, we can't get rid of the massive switch case statement.

Example:

func handle(_ error: Error) {
	switch error {
	case is APIException:
		guard let error = error as? APIException else { break }
		handle(error) //call APIException handler function
	case is ValidationException:
		guard let error = error as? APIException else { break }
		handle(error) //call ValidationException handler function
	//etc.
	}
}

The best solution would be to provide separate methods which receive an «Error» instance as an incoming parameter and return an optional «ErrorHandler» instance as a result.

Example:

protocol ErrorHandler {}

extension ErrorHandler {
	func handleAPIException(_ error: Error) -> Self? {
		guard let error = error as? APIException else { return self }
		//handle error as api exception
		return nil
	}
	
	func handleValidationException(_ error: Error) -> Self? {
		guard let error = error as? ValidationException else { return self }
		// handle error as validation exception
		return nil
	}
}

You may be wondering: what is the purpose of returning the ErrorHandler instance? The purpose is to enable a handler’s usage in chain order.

Example:

extension ErrorHandler {
	func handle(_ error: Error) {
		handleAPIException(error)?.handleValidationException()
	}
}

The optional result is to avoid the multiple handling of the same error, e.g., when the handler can handle a certain type of error, it returns «nil» as a result, and the following handlers will not be called.


BE THE FIRST WHO GETS UPDATES
Using Corsac Blog and website you agree to our Privacy Policy and Terms and Conditions.