Exception Handler in Class

1.

2.   ExceptionhandlingApplication class


package com.Exceptionhandling;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ExceptionhandlingApplication {

public static void main(String[] args) {
SpringApplication.run(ExceptionhandlingApplication.class, args);
}
}

3. Application.properties

server.port=9009
spring.thymeleaf.cache=false

4.  POM.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.Exceptionhandling</groupId>
<artifactId>Exceptionhandling</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>Exceptionhandling</name>
<description>errorhandling project for Spring Boot</description>

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.10.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>


</project>

5.  Post class 
package com.Exceptionhandling.domain;


import java.util.Date;
public class Post {

private String title;
private String body;
private Date posted;
private String author;

public Post() {
}

public String getTitle() {
return title;
}

public void setTitle(String title) {
this.title = title;
}

public String getBody() {
return body;
}

public void setBody(String body) {
this.body = body;
}

public Date getPosted() {
return posted;
}

public void setPosted(Date posted) {
this.posted = posted;
}

public String getAuthor() {
return author;
}

public void setAuthor(String author) {
this.author = author;
}

@Override
public String toString() {
return "Post [title=" + title + "]";
}
}

6.  PostController Class
package com.Exceptionhandling.controller;


import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;


@Controller
@RequestMapping("/posts")
public class PostController {
private static final Logger logger = LoggerFactory.getLogger(PostController.class);
@RequestMapping("/get/{slug}")
public String getPost(@PathVariable(value="slug") String slug) throws Exception{
com.Exceptionhandling.domain.Post post = null;
if( post == null ) throw new Exception("We couldn't find the post with slug: " + slug);
return "post";
}
@ExceptionHandler(Exception.class)
public String handleException(HttpServletRequest req, Exception exception, Model model){
model.addAttribute("errorMessage", exception.getMessage() );
return "postError";
}
}

7. PostError.html
<!DOCTYPE html>
<html lang="en"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymleaf.org">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Page Not Found</title>
<link rel="stylesheet" href="../static/css/blog.css" th:href="@{/css/blog.css}"/>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" />

<!--[if lt IE 9]>
  <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
  <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>

<div class="container">
<nav class="navbar navbar-default">
    <div class="container-fluid">
        <div class="navbar-header">
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-5" aria-expanded="false">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="#">therealdanvega.com</a>
        </div>
        <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-5">
            <p class="navbar-text navbar-right">Signed in as <a href="#" class="navbar-link">Guest User</a></p>
        </div>
    </div>
</nav>
<h2>Page Not Found</h2>
<p th:text="${errorMessage}">error message</p>
<p>Maybe you would like one of these posts</p>
<ul>
<li>Post 1</li>
<li>Post 2</li>
<li>Post 3</li>
</ul>
</div>

</body>
</html>

7. Run the program




=====================================================

Global Exception handler

8. Now modify code PostController Class

package com.Exceptionhandling.controller;


import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;


@Controller
@RequestMapping("/posts")
public class PostController {
private static final Logger logger = LoggerFactory.getLogger(PostController.class);
@RequestMapping("/get/{slug}")
public String getPost(@PathVariable(value="slug") String slug) throws Exception{
com.Exceptionhandling.domain.Post post = null;
if( post == null ) throw new Exception("We couldn't find the post with slug: " + slug);
return "post";
}
/*
@ExceptionHandler(Exception.class)
public String handleException(HttpServletRequest req, Exception exception, Model model){
model.addAttribute("errorMessage", exception.getMessage() );
return "postError";
}
*/
}

9. ErrorHandler.html
<!DOCTYPE html>
<html lang="en"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymleaf.org">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Global Handler</title>
<link rel="stylesheet" href="../static/css/blog.css" th:href="@{/css/blog.css}"/>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" />

<!--[if lt IE 9]>
  <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
  <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>

<div class="container">
<nav class="navbar navbar-default">
    <div class="container-fluid">
        <div class="navbar-header">
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-5" aria-expanded="false">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="#">therealdanvega.com</a>
        </div>
        <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-5">
            <p class="navbar-text navbar-right">Signed in as <a href="#" class="navbar-link">Guest User</a></p>
        </div>
    </div>
</nav>
<h2>Global Handler</h2>
<p th:text="${exception}">Exception</p>
</div>

</body>
</html>

10. Now Create  ExceptionControllerAdvice Class

package com.Exceptionhandling.controller;


import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

@ControllerAdvice
public class ExceptionControllerAdvice {

@ExceptionHandler(Exception.class)
public String exception(Exception exception, Model model){
model.addAttribute("exception", exception);
return "errorHandler";
}
}

11. Run the program.




Comments