everyone. I am new to Swift, and trying to handle custom errors in my project. Unfortunately, during errors I always encounter print(“DEBUG: Unknown error occurred: …”). For example, if error is ‘invalidURL’ I have ‘DEBUG: Unknown error occurred: A server with the specified hostname could not be found.’ and so on.
Any ideas how i can make it work? Thank you in advance.
Here is my function from DataService:
func getEnemy() async throws -> Enemy {
guard let url = URL(string: urlString) else {
throw EnemyAPIError.invalidURL
}
let (data, response) = try await urlSession.data(for: url)
guard let httpResponse = response as? HTTPURLResponse else {
print("DEBUG: Bad Server Response")
throw EnemyAPIError.badServerResponse
}
guard httpResponse.statusCode == 200 else {
print("DEBUG: Failed to fetch with status code: (httpResponse.statusCode)")
throw EnemyAPIError.invalidStatusCode(statusCode: httpResponse.statusCode)
}
guard !data.isEmpty else {
throw EnemyAPIError.invalidData
}
let enemy = try JSONDecoder().decode(Enemy.self, from: data)
return enemy
}
In my viewModel I am trying to handle custom errors:
func fetchEnemyAsync() async {
do{
self.enemy = try await networkService.getEnemy()
} catch let error as EnemyAPIError {
self.errorMessage = error.customDescription
print("DEBUG: Error occurred: (error.customDescription)")
}
catch {
print("DEBUG: Unknown error occurred: (error.localizedDescription)")
self.errorMessage = "(error.localizedDescription)"
}
}
My custom errors:
enum EnemyAPIError: Error{
case invalidData
case invalidURL
case jsonParsingFailure
case badServerResponse
case requestFailed(description: String)
case invalidStatusCode(statusCode: Int)
case unknownError(error: Error)
var customDescription: String {
switch self {
case .invalidData:
return "Invalid data"
case .invalidURL:
return "Invalid URL"
case .jsonParsingFailure:
return "Failed to parse JSON"
case .badServerResponse:
return "Bad Server Response"
case .requestFailed(let description):
return "Request failed: (description)"
case .invalidStatusCode(let statusCode):
return "Invalid status code: (statusCode)"
case .unknownError(let error):
return "(error.localizedDescription)"
}
}
}
In my viewModel i’ve tried to handle errors like this, but it doesn’t work. I thought, it will catch any error of type EnemyAPIError.
func fetchEnemyAsync() async {
do{
self.enemy = try await networkService.getEnemy()
} catch let error as EnemyAPIError {
self.errorMessage = error.customDescription
print("DEBUG: Error occurred: (error.customDescription)")
}
Vladyslav is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.