I have several methods that look like this:
public void foo()
{
try
{
doSomething();
}
catch(Exception e)
{
Log.Error(e);
}
}
Can I change the code to look like?
[LogException()]
public void foo()
{
doSomething();
}
How can I implement this custom attribute? and what are the pros and cons of doing it?
-----Edit 1------------
Can I implemented it myself, I mean just write one class, or do I need to use postsharp or another solution?
To avoid writing multiple try catch async await in a function, a better option is to create a function to wrap each try catch. The first result of the promise returns an array where the first element is the data and the second element is an error. And if there's an error, then the data is null and the error is defined.
Core Java bootcamp program with Hands on practiceYes, It is possible to have a try block without a catch block by using a final block. As we know, a final block will always execute even there is an exception occurred in a try block, except System.
Yes, we can define one try block with multiple catch blocks in Java. Every try should and must be associated with at least one catch block.
You cannot have multiple try blocks with a single catch block. Each try block must be followed by catch or finally. Still if you try to have single catch block for multiple try blocks a compile time error is generated.
You can use delegates and lambdas:
private void ExecuteWithLogging(Action action) {
try {
action();
} catch (Exception e) {
Log.Error(e);
}
}
public void fooSimple() {
ExecuteWithLogging(doSomething);
}
public void fooParameter(int myParameter) {
ExecuteWithLogging(() => doSomethingElse(myParameter));
}
public void fooComplex(int myParameter) {
ExecuteWithLogging(() => {
doSomething();
doSomethingElse(myParameter);
});
}
In fact, you could rename ExecuteWithLogging
to something like ExecuteWebserviceMethod
and add other commonly used stuff, such as checking credentials, opening and closing a database connection, etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With