Home > Software engineering >  Controller advice in Spring MVC
Controller advice in Spring MVC

Time:03-14

I have some problems regarding Controller usage in Spring.

Preferably, I would like to keep the Controller methods small and simply use them to call a Service function as follows:

@Controller
class controllerClass {
    @RequestMapping("/foo/")
    public void foo(Model model) {
        Data returnedData = fooServiceFunction();
        model.addAttribute("data", returnedData);
    }
}

@Service
class serviceClass {
    fooServiceFunction() {
        Data data = methodCall();
        methodCall2();
        methodCall3();

        return data;
    }
}

However, in practise I have found this implementation difficult because I have found myself needing to check if the methods called from within the fooServiceFunction() succeeded or failed. I have been returning a custom 'Status' class from these functions which is passed to the controller to signal if the methods have executed successfully and/or any errors that have occurred (validation errors, etc.).

Now, this is fine if I do not need to return any data. But if I want to return data from the Service function and pass it to the Controller, this would mean I would need to make a custom class for EVERY Controller method which would contain:

a) the data.
b) the success status

which just seems unreasonable.

I have considered just throwing Exceptions to indicate a failure, but this doesn't seem proper.

Is there a better way? What is the optimal way to handle these situations? Or should I just write fat Controller methods that implement more of the application/business logic?

Thank you.

CodePudding user response:

I think the best approach would be to throw a custom exception and then use a class annotated with

@ControllerAdvice

to deal with that exception and make it return a ResponseEntity customized according to your needs. This way the line

return data;

will only occur if there are no exceptions

  • Related