Exception handler - Spring

4 views
Skip to first unread message

kathire...@gmail.com

unread,
Feb 15, 2018, 9:41:09 PM2/15/18
to Getting started with Spring Framework

Went through the link https://www.mkyong.com/spring-boot/spring-boot-ajax-example/

and observed the following

  1. Don't type any name and hit search button - Bad Request - It Comes to Error Function of Ajax - User Can't be Empty - Form Validation. Ajax response is error in this case.

  2. Type "Raju" in name field and hit search button - Business Error - Returned with Success Function. Ajax response is success in this case.

  3. Assume i have thrown a run time exception in getSearchResultViaAjax() as below

AjaxResponseBody result = new AjaxResponseBody();

    if(1==1) { 
          throw new RuntimeException(); 
    } 

The same Ajax error block is getting called.

  error: function (e) { 

        var json = "<h4>Ajax Response Error </h4><pre>" 
            + e.responseText + "</pre>"; 
        $('#feedback').html(json); 

        console.log("ERROR pp : ", e); 
        $("#btn-search").prop("disabled", false); 

    } 

So for Bad Request and Any Exception which comes Out side the box comes in error block

Which would be the correct approach in the following ? If both of them is incorrect, help me with the best practice

Approach One

  1. Throw form validation errors as as Ajax Response is ERROR with failure message to display
  2. Throw Business validation errors as Ajax Response is SUCCESS with failure message to display
  3. Throw any other exception as Ajax Response is ERROR with failure message to display

OR

Approach Two

  1. Throw form validation error as Ajax Response is ERROR with failure message to display ('User Field is Empty')
  2. Throw Business validation errors as Ajax Response is FAILURE with failure message to display ('User Name doesn't exist')
  3. Throw any other exception as Ajax Response is ERROR with failure message to display

What would be the best approach or best practice ?

Reply all
Reply to author
Forward
0 new messages