开发者

Handling database errors

I am using an MVC framework in my application, so currently when I detect an error has occurred while working with the database in my model, I am throwing exceptions back to the controller.

//db querying
//doing more db querying...
if (error)
    throw new ApiException('Unable to connect to User database', 1, 500);
else if (another type of error)
    throw new StampApiException('Could not retrieve the User', 12, 5开发者_开发百科00);

return $user;

Most of the time I find this to be nice as I can just have the controller print the error to the screen, thus keeping all error codes etc... in the model. But at times this can make the code quite messy and harder to deal with.

Is this a good way to be handling such errors? Or is there a better/more standard way?


Fisrt, I would say the user does not need to know if the problem is the database, the admin password or the memory. Just have a technical error page for the user, and log the error detail on the server, for your debug.

For the technical problems you are talking about, the best is to have a central treatment to manage them, i.e. throw an error page. The usual place is the dispatcher of the controller. If you're using a framework, this mechanism should exist (symfony for example). This way, you don't have to mess with these exceptions in your actual code.

Just like you found it, the best policy is to catch an exception only when you can do something about it.

For example :

  • a "database access problem" can be automatically treated by the dispatcher. So you don't catch it in your code en let it to the central treatment
  • a "user not found" may have a specific treatment from your controller, to propose creation for example. So you catch it.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜