{"id":58916,"date":"2023-10-04T08:30:39","date_gmt":"2023-10-04T03:00:39","guid":{"rendered":"https:\/\/www.tothenew.com\/blog\/?p=58916"},"modified":"2024-01-02T17:37:04","modified_gmt":"2024-01-02T12:07:04","slug":"custom-exceptional-handling-using-controlleradvice","status":"publish","type":"post","link":"https:\/\/www.tothenew.com\/blog\/custom-exceptional-handling-using-controlleradvice\/","title":{"rendered":"Custom Exceptional Handling using ControllerAdvice"},"content":{"rendered":"<p id=\"76e5\" class=\"pw-post-body-paragraph abw abx wu nr b aby abz aca acb acc acd ace acf nb acg ach aci ng acj ack acl nl acm acn aco acp kc bp\" data-selectable-paragraph=\"\"><img decoding=\"async\" loading=\"lazy\" class=\"bm abu abv c alignleft\" role=\"presentation\" src=\"\/blog\/wp-ttn-blog\/uploads\/2024\/01\/1AYhaa0lF5Sxfj7R3ukf9qA.png\" alt=\"\" width=\"700\" height=\"308\" \/><\/p>\n<p class=\"pw-post-body-paragraph abw abx wu nr b aby abz aca acb acc acd ace acf nb acg ach aci ng acj ack acl nl acm acn aco acp kc bp\" style=\"text-align: left;\" data-selectable-paragraph=\"\">Here, we can see in the above image that the product is not present for this product ID. But we are getting proper 200 status. which is not a proper understandable response.<\/p>\n<h2 id=\"ffe7\" class=\"pw-post-body-paragraph abw abx wu nr b aby abz aca acb acc acd ace acf nb acg ach aci ng acj ack acl nl acm acn aco acp kc bp\" style=\"text-align: left;\"><strong class=\"nr gk\">Let\u2019s understand why we need Custom Exceptional Handing<\/strong><\/h2>\n<p id=\"5099\" class=\"pw-post-body-paragraph abw abx wu nr b aby abz aca acb acc acd ace acf nb acg ach aci ng acj ack acl nl acm acn aco acp kc bp\" style=\"text-align: left;\" data-selectable-paragraph=\"\">Using <code class=\"cn acq acr acs act b\">@ControllerAdvice<\/code> in Spring allows you to create a centralized exception handler that can handle exceptions thrown by controllers in your application. This is a powerful feature for custom exception handling. Here&#8217;s a step-by-step guide on how to implement custom exception handling using <code class=\"cn acq acr acs act b\">@ControllerAdvice<\/code> in Spring:<\/p>\n<h3 id=\"e746\" class=\"pw-post-body-paragraph abw abx wu nr b aby abz aca acb acc acd ace acf nb acg ach aci ng acj ack acl nl acm acn aco acp kc bp\" style=\"text-align: left;\"><strong class=\"nr gk\">Step 1: Create Custom Exception Classes<\/strong><\/h3>\n<p id=\"410f\" class=\"pw-post-body-paragraph abw abx wu nr b aby abz aca acb acc acd ace acf nb acg ach aci ng acj ack acl nl acm acn aco acp kc bp\" style=\"text-align: left;\" data-selectable-paragraph=\"\">Create custom exception classes that extend <code class=\"cn acq acr acs act b\">RuntimeException<\/code> Or a suitable base exception class. For example:<\/p>\n<pre class=\"acu acv acw acx acy acz act ada lr adb bh bp\"><span id=\"c8fe\" class=\"rc adc wu act b bl add ade s adf adg\" data-selectable-paragraph=\"\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title.class\">ProductNotFoundException<\/span> <span class=\"hljs-keyword\">extends<\/span> <span class=\"hljs-title.class\">RuntimeException<\/span> {\r\n    <span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-title.function\">ProductNotFoundException<\/span><span class=\"hljs-params\">(String message)<\/span> {\r\n        <span class=\"hljs-built_in\">super<\/span>(message);\r\n    }\r\n}<\/span><\/pre>\n<pre class=\"sl acz act ada lr adb bh bp\"><span id=\"382f\" class=\"rc adc wu act b bl add ade s adf adg\" data-selectable-paragraph=\"\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title.class\">InvalidRequestException<\/span> <span class=\"hljs-keyword\">extends<\/span> <span class=\"hljs-title.class\">RuntimeException<\/span> {\r\n    <span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-title.function\">InvalidRequestException<\/span><span class=\"hljs-params\">(String message)<\/span> {\r\n        <span class=\"hljs-built_in\">super<\/span>(message);\r\n    }\r\n}<\/span><\/pre>\n<p id=\"9f2b\" class=\"pw-post-body-paragraph abw abx wu nr b aby abz aca acb acc acd ace acf nb acg ach aci ng acj ack acl nl acm acn aco acp kc bp\" style=\"text-align: left;\" data-selectable-paragraph=\"\">You can create as many custom exception classes as needed for different error scenarios.<\/p>\n<h3 id=\"6fdb\" class=\"pw-post-body-paragraph abw abx wu nr b aby abz aca acb acc acd ace acf nb acg ach aci ng acj ack acl nl acm acn aco acp kc bp\" style=\"text-align: left;\"><strong class=\"nr gk\">Step 2: Create a Global Exception Handler<\/strong><\/h3>\n<p id=\"2496\" class=\"pw-post-body-paragraph abw abx wu nr b aby abz aca acb acc acd ace acf nb acg ach aci ng acj ack acl nl acm acn aco acp kc bp\" style=\"text-align: left;\" data-selectable-paragraph=\"\">Create a global exception handler class annotated with <code class=\"cn acq acr acs act b\">@ControllerAdvice<\/code>. This class will contain methods to handle various exceptions.<\/p>\n<p class=\"pw-post-body-paragraph abw abx wu nr b aby abz aca acb acc acd ace acf nb acg ach aci ng acj ack acl nl acm acn aco acp kc bp\" style=\"text-align: left;\" data-selectable-paragraph=\"\">Here&#8217;s an example:<\/p>\n<pre class=\"acu acv acw acx acy acz act ada lr adb bh bp\"><span id=\"27e0\" class=\"rc adc wu act b bl add ade s adf adg\" data-selectable-paragraph=\"\"><span class=\"hljs-meta\">@ControllerAdvice<\/span>\r\n<span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title.class\">GlobalExceptionHandler<\/span> {\r\n\r\n    <span class=\"hljs-meta\">@ExceptionHandler(ProductNotFoundException.class)<\/span>\r\n    <span class=\"hljs-keyword\">public<\/span> ResponseEntity&lt;String&gt; <span class=\"hljs-title.function\">handleProductNotFoundException<\/span><span class=\"hljs-params\">(ProductNotFoundException ex)<\/span> {\r\n        <span class=\"hljs-keyword\">return<\/span> <span class=\"hljs-keyword\">new<\/span> <span class=\"hljs-title.class\">ResponseEntity<\/span>&lt;&gt;(ex.getMessage(), HttpStatus.NOT_FOUND);\r\n    }\r\n\r\n    <span class=\"hljs-meta\">@ExceptionHandler(InvalidRequestException.class)<\/span>\r\n    <span class=\"hljs-keyword\">public<\/span> ResponseEntity&lt;String&gt; <span class=\"hljs-title.function\">handleInvalidRequestException<\/span><span class=\"hljs-params\">(InvalidRequestException ex)<\/span> {\r\n        <span class=\"hljs-keyword\">return<\/span> <span class=\"hljs-keyword\">new<\/span> <span class=\"hljs-title.class\">ResponseEntity<\/span>&lt;&gt;(ex.getMessage(), HttpStatus.BAD_REQUEST);\r\n    }\r\n\r\n    <span class=\"hljs-meta\">@ExceptionHandler(Exception.class)<\/span>\r\n    <span class=\"hljs-keyword\">public<\/span> ResponseEntity&lt;String&gt; <span class=\"hljs-title.function\">handleOtherExceptions<\/span><span class=\"hljs-params\">(Exception ex)<\/span> {\r\n        <span class=\"hljs-keyword\">return<\/span> <span class=\"hljs-keyword\">new<\/span> <span class=\"hljs-title.class\">ResponseEntity<\/span>&lt;&gt;(<span class=\"hljs-string\">\"An error occurred: \"<\/span> + ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);\r\n    }\r\n}<\/span><\/pre>\n<p id=\"29c0\" class=\"pw-post-body-paragraph abw abx wu nr b aby abz aca acb acc acd ace acf nb acg ach aci ng acj ack acl nl acm acn aco acp kc bp\" style=\"text-align: left;\" data-selectable-paragraph=\"\">In this example, we\u2019ve created three exception-handling methods: one for handling <code class=\"cn acq acr acs act b\">ProductNotFoundException<\/code>, one for handling <code class=\"cn acq acr acs act b\">InvalidRequestException<\/code>, and another for handling general exceptions. These methods return appropriate HTTP response statuses and error messages.<\/p>\n<h3 id=\"831a\" class=\"pw-post-body-paragraph abw abx wu nr b aby abz aca acb acc acd ace acf nb acg ach aci ng acj ack acl nl acm acn aco acp kc bp\" style=\"text-align: left;\"><strong class=\"nr gk\">Step 3: Throw Custom Exceptions in Your Controllers<\/strong><\/h3>\n<p id=\"7cda\" class=\"pw-post-body-paragraph abw abx wu nr b aby abz aca acb acc acd ace acf nb acg ach aci ng acj ack acl nl acm acn aco acp kc bp\" style=\"text-align: left;\" data-selectable-paragraph=\"\">In your controller methods, throw custom exceptions when needed. For example:<\/p>\n<pre class=\"acu acv acw acx acy acz act ada lr adb bh bp\"><span id=\"9e56\" class=\"rc adc wu act b bl add ade s adf adg\" data-selectable-paragraph=\"\"><span class=\"hljs-meta\">@RestController<\/span>\r\n<span class=\"hljs-meta\">@RequestMapping(\"\/api\/products\")<\/span>\r\n<span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title.class\">ProductController<\/span> {\r\n    <span class=\"hljs-meta\">@Autowired<\/span>\r\n    <span class=\"hljs-keyword\">private<\/span> ProductService productService;\r\n\r\n    <span class=\"hljs-meta\">@GetMapping(\"\/{id}\")<\/span>\r\n    <span class=\"hljs-keyword\">public<\/span> ResponseEntity&lt;Product&gt; <span class=\"hljs-title.function\">getProductById<\/span><span class=\"hljs-params\">(<span class=\"hljs-meta\">@PathVariable<\/span> Long id)<\/span> {\r\n        <span class=\"hljs-type\">Product<\/span> <span class=\"hljs-variable\">product<\/span> <span class=\"hljs-operator\">=<\/span> productService.getProductById(id);\r\n        <span class=\"hljs-keyword\">if<\/span> (product == <span class=\"hljs-literal\">null<\/span>) {\r\n            <span class=\"hljs-keyword\">throw<\/span> <span class=\"hljs-keyword\">new<\/span> <span class=\"hljs-title.class\">ProductNotFoundException<\/span>(<span class=\"hljs-string\">\"Product not found with ID: \"<\/span> + id);\r\n        }\r\n        <span class=\"hljs-keyword\">return<\/span> ResponseEntity.ok(product);\r\n    }\r\n\r\n    <span class=\"hljs-meta\">@PostMapping<\/span>\r\n    <span class=\"hljs-keyword\">public<\/span> ResponseEntity&lt;String&gt; <span class=\"hljs-title.function\">createProduct<\/span><span class=\"hljs-params\">(<span class=\"hljs-meta\">@RequestBody<\/span> Product product)<\/span> {\r\n        <span class=\"hljs-keyword\">if<\/span> (product == <span class=\"hljs-literal\">null<\/span>) {\r\n            <span class=\"hljs-keyword\">throw<\/span> <span class=\"hljs-keyword\">new<\/span> <span class=\"hljs-title.class\">InvalidRequestException<\/span>(<span class=\"hljs-string\">\"Invalid product request\"<\/span>);\r\n        }\r\n        productService.createProduct(product);\r\n        <span class=\"hljs-keyword\">return<\/span> ResponseEntity.status(HttpStatus.CREATED).body(<span class=\"hljs-string\">\"Product created successfully\"<\/span>);\r\n    }\r\n    <span class=\"hljs-comment\">\/\/ Other controller methods<\/span>\r\n}<\/span><\/pre>\n<p id=\"35a4\" class=\"pw-post-body-paragraph abw abx wu nr b aby abz aca acb acc acd ace acf nb acg ach aci ng acj ack acl nl acm acn aco acp kc bp\" style=\"text-align: left;\" data-selectable-paragraph=\"\">In this example, when a product is not found (<code class=\"cn acq acr acs act b\">getProductById<\/code>) or an invalid request is made (<code class=\"cn acq acr acs act b\">createProduct<\/code>), we throw custom exceptions (<code class=\"cn acq acr acs act b\">ProductNotFoundException<\/code> and <code class=\"cn acq acr acs act b\">InvalidRequestException<\/code>).<\/p>\n<h3 id=\"af06\" class=\"pw-post-body-paragraph abw abx wu nr b aby abz aca acb acc acd ace acf nb acg ach aci ng acj ack acl nl acm acn aco acp kc bp\" style=\"text-align: left;\"><strong class=\"nr gk\">Step 4: Test the Exception Handling<\/strong><\/h3>\n<p id=\"91b3\" class=\"pw-post-body-paragraph abw abx wu nr b aby abz aca acb acc acd ace acf nb acg ach aci ng acj ack acl nl acm acn aco acp kc bp\" style=\"text-align: left;\" data-selectable-paragraph=\"\">Now, when you access your RESTful endpoints and an exception is thrown, the global exception handler will catch the exception and return the appropriate HTTP status and error message.<\/p>\n<p id=\"da21\" class=\"pw-post-body-paragraph abw abx wu nr b aby abz aca acb acc acd ace acf nb acg ach aci ng acj ack acl nl acm acn aco acp kc bp\" style=\"text-align: left;\" data-selectable-paragraph=\"\">For example, if you make a GET request to <code class=\"cn acq acr acs act b\">\/api\/products\/123<\/code>, and a product with ID 123 is not found, the response will have a status code of 404 (NOT FOUND) and an error message like &#8220;Product not found with ID: 123.&#8221;<\/p>\n<p id=\"e420\" class=\"pw-post-body-paragraph abw abx wu nr b aby abz aca acb acc acd ace acf nb acg ach aci ng acj ack acl nl acm acn aco acp kc bp\" style=\"text-align: left;\" data-selectable-paragraph=\"\">By following these steps, you\u2019ve added custom exception handling using <code class=\"cn acq acr acs act b\">@ControllerAdvice<\/code> in your Spring Boot application, allowing you to handle specific exceptions gracefully and provide meaningful error responses to clients.<\/p>\n<figure class=\"acu acv acw acx acy abp lz ma paragraph-image\">\n<div class=\"abq abr by abs bm abt\" role=\"button\">\n<div class=\"lz ma abj\"><img decoding=\"async\" loading=\"lazy\" class=\"bm abu abv c\" role=\"presentation\" src=\"\/blog\/wp-ttn-blog\/uploads\/2024\/01\/1bnnVpE_tWprLZ2WsThxDQA.png\" alt=\"\" width=\"700\" height=\"308\" \/><\/div>\n<\/div>\n<\/figure>\n<p id=\"67a0\" class=\"pw-post-body-paragraph abw abx wu nr b aby abz aca acb acc acd ace acf nb acg ach aci ng acj ack acl nl acm acn aco acp kc bp\" style=\"text-align: left;\" data-selectable-paragraph=\"\">After we fix this issue, we&#8217;ll be getting a proper response. You can have a look at the code here on <a class=\"ay hj\" href=\"https:\/\/github.com\/themoinmalik\/ExceptionHandling\" target=\"_blank\" rel=\"noopener ugc nofollow\">github<\/a>.<\/p>\n<p id=\"5260\" class=\"pw-post-body-paragraph abw abx wu nr b aby abz aca acb acc acd ace acf nb acg ach aci ng acj ack acl nl acm acn aco acp kc bp\" style=\"text-align: left;\" data-selectable-paragraph=\"\">You can comment down below or email me your queries.<\/p>\n<div class=\"ap-custom-wrapper\"><\/div><!--ap-custom-wrapper-->","protected":false},"excerpt":{"rendered":"<p>Here, we can see in the above image that the product is not present for this product ID. But we are getting proper 200 status. which is not a proper understandable response. Let\u2019s understand why we need Custom Exceptional Handing Using @ControllerAdvice in Spring allows you to create a centralized exception handler that can handle [&hellip;]<\/p>\n","protected":false},"author":1507,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"iawp_total_views":34},"categories":[446,1994,3109],"tags":[5489],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts\/58916"}],"collection":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/users\/1507"}],"replies":[{"embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/comments?post=58916"}],"version-history":[{"count":4,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts\/58916\/revisions"}],"predecessor-version":[{"id":59656,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts\/58916\/revisions\/59656"}],"wp:attachment":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/media?parent=58916"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/categories?post=58916"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/tags?post=58916"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}