Postsharp: How to set the return value after an exception
Asked Answered
S

1

6

Using Postsharp, how do you set the return value after an exception has been thrown?

I thought this would work:

namespace MvcApplication3.Controllers
{
    public class ValuesController : ApiController
    {
        // GET api/values/5
        [MyExceptionHandler]
        public string Get(int id)
        {
            string value = GetValue(id);
            return value;
        }

        private string GetValue(int id)
        {
            throw new DivideByZeroException();
        }
    }

    [Serializable]
    public class MyExceptionHandler : OnExceptionAspect
    {
        public override void OnException(MethodExecutionArgs args)
        {
            args.FlowBehavior = FlowBehavior.Continue;
            args.ReturnValue = "Error Getting Value";
        }
    }
}
Stesha answered 20/2, 2014 at 5:29 Comment(0)
S
7

I figured it out.

You need to Return from the function, not continue.

    public override void OnException(MethodExecutionArgs args)
    {
        args.FlowBehavior = FlowBehavior.Return;
        args.ReturnValue = "Error Getting Value";
    }
Stesha answered 20/2, 2014 at 5:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.