I'm trying to get access to thrown errors. So for instance if a user had an array of 3 elements and tried accessing the fourth, I'd like to capture the out of bounds error and then process it.
My project is just trying to return better error messages in general. I haven't really thought that much about what i'd do after capturing the error but I know thats step one.
My thought was maybe I could extend Error and see if theres a function that gets called whenever Error is thrown but I don't think there is and I don't think Error is always thrown when a program crashes.
Is it possible to capture errors?
Out of bounds errors are described in the Error Handling Rationale fundamental document as "logic failures":
The final category is logic failures, including out of bounds array accesses, forced unwrap of
nil optionals, and other kinds of assertions. The programmer has made a mistake, and the failure should be handled by fixing the code, not by attempting to recover dynamically.
As the recommended handling of such an error is fixing the code, those errors are currently not recoverable at all: the program crashes and you handle them by... fixing your code.
However the door is not closed. The rationale continues:
The correct handling of these error conditions is an open question and is not a focus of this proposal. Should we decide to make them recoverable, they will likely follow the same implementation mechanism as universal errors, if not necessarily the same language rules.
And indeed there are plans to make them recoverable in a future Swift version. See the [Concurrency] async/await + actors thread, and especially this chapter of the pitch: Part 3: Reliability through fault isolation
Until then (Swift 6? 7?), it is highly unlikely that you will be able to capture out-of-bounds errors.
Even capturing after the program crashes? I'm not looking to fix the program dynamically, just looking to print a better error message. I don't mind the program crashing.
Then what about processing the error message itself after it has been emitted by the crashing program? The question is now: where is this error message emitted, so that you can plug your processing?
It is likely to depend on the way you run your crashing program. Is it a command line tool? Check stderr. Is it an iOS app? The error message is likely sent to the system logger, and I don't know if you can process it there (there are big old master sorcerers on this forum who may help you do this, but be ready for low-level OS tricks). From now on, you have to provide more details if you want help.
No much details to share at the moment. Your last message is a good place to start. It would be a command line tool I guess that just read the error message, looked it up in some table and returned a better error message. I'll look into reading from stderr