ASP.NET - displaying business layer errors in the presentation layer

前端 未结 1 1179
日久生厌
日久生厌 2021-01-26 12:52

Currently in the ASP.NET application I\'m developing, basic validations (ie required fields) are being done in the Presentation Layer, using Validators and a ValidationSummary.

相关标签:
1条回答
  • 2021-01-26 13:32

    There are essentially two ways to do this: either by passing back an error code/object from your business layer, or throw out an exception. You can also combine both.

    For an example, you can take a look SqlException class. When you send a SQL to SQL Server, it runs a query parser to parse your SQL first. If it sees syntax error, then it will throw out a SqlException and terminate the query. There may be multiple syntax errors in your query. So SqlExeption class has an Errors property that contains a list of errors. You can then enumerate through that list in your presentation layer to format your error message, probably with a CustomValidator.

    You can also simply just return the error list without throwing an exception. For example, you can have your function to return a List in case at least one error occurred and return null in case the call was successful. Or you can pass List as an argument into your function. They are all fine, it all depends on which way you feel is more convenient. The advantage of throwing out an exception is it unwinds multiple call frames immediately, so you don’t have to check return value on every level. For example, if function A calls function B , B calls function C, C sees something wrong, then if let C to return an error object (or error code), then B has to have code to check whether C returned an error and pass that error code/value back, A have to check it as well ---- you need to check it on every level. On the other hand, if you just let C to throw an exception, then the code goes straight to the exception handler. You don’t have check return values on every level.

    0 讨论(0)
提交回复
热议问题