| 43 | == Error Handling == |
| 44 | Use the appropriate method to handle errors:: |
| 45 | For errors that are of interest to the user, use one of the Error.addXXXMessage functions to print an error/warning message. Always supply the source info when posssible, i.e. prefer using addSourceMessage or addMultiSourceMessage. For cases where it might be of interest to the developers if a function fails, use failtrace and Debug.traceXXX: |
| 46 | {{{#!mo |
| 47 | if Flags.isSet(Flags.FAILTRACE) then |
| 48 | Debug.traceln("- Foo.bar failed!"); |
| 49 | end if; |
| 50 | }}} |
| 51 | For functions that should never fail, use internal errors: |
| 52 | {{{#!mo |
| 53 | function foo |
| 54 | input Integer inN; |
| 55 | algorithm |
| 56 | if inN < 0 then |
| 57 | Error.addInternalError("Negative number given to foo!", sourceInfo()); |
| 58 | end if; |
| 59 | end foo; |
| 60 | }}} |
| 61 | Only print internal errors as a last resort:: |
| 62 | Internal errors should only be used when something has gone really wrong, and ideally they should never be shown to users. In many cases it's therefore appropriate to check that some other error hasn't already been printed before printing an internal error: |
| 63 | {{{#!mo |
| 64 | function foo |
| 65 | ... |
| 66 | protected |
| 67 | Integer err_count = Error.getNumErrorMessages(); |
| 68 | algorithm |
| 69 | try |
| 70 | // Something which can fail, and might or might not print an error message if it does fail. |
| 71 | else |
| 72 | // Only print an internal error if the above code failed without printing an error message. |
| 73 | if err_count == Error.getNumErrorMessages() then |
| 74 | Error.addInternalError(...); |
| 75 | end if; |
| 76 | end try; |
| 77 | end foo; |
| 78 | }}} |