Skip to content

Commit

Permalink
Exception handler
Browse files Browse the repository at this point in the history
  • Loading branch information
jwierzbo committed Feb 8, 2018
1 parent 9a5a155 commit cf57393
Show file tree
Hide file tree
Showing 7 changed files with 54 additions and 48 deletions.
30 changes: 15 additions & 15 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -3,25 +3,25 @@
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>

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.10.RELEASE</version>
</parent>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.10.RELEASE</version>
</parent>

<groupId>net.jwierzbo.rest</groupId>
<artifactId>REST-movie-service</artifactId>
<version>0.1</version>
<groupId>net.jwierzbo.rest</groupId>
<artifactId>REST-movie-service</artifactId>
<version>0.1</version>
<packaging>jar</packaging>
<name>Movie app - Spring Boot REST with CRUD example</name>
<name>Movie app - Spring Boot REST with CRUD example</name>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
<swagger.lib.version>2.8.0</swagger.lib.version>
</properties>
</properties>

<dependencies>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
Expand All @@ -44,7 +44,7 @@
<version>${swagger.lib.version}</version>
<scope>compile</scope>
</dependency>
</dependencies>
</dependencies>

<build>
<plugins>
Expand Down
19 changes: 19 additions & 0 deletions src/main/java/net/jwierzbo/rest/api/GlobalExceptionController.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package net.jwierzbo.rest.api;

import net.jwierzbo.rest.exception.MovieNotFoundException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

@ControllerAdvice
public class GlobalExceptionController {

@ResponseStatus(value= HttpStatus.NOT_FOUND)
@ExceptionHandler(MovieNotFoundException.class)
@ResponseBody
public String handleAllException(MovieNotFoundException ex) {
return "GLOBAL-application handler: " + ex.getMessage();
}
}
16 changes: 8 additions & 8 deletions src/main/java/net/jwierzbo/rest/api/MovieV1RestController.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
Expand All @@ -24,6 +25,12 @@
@RequestMapping("/v1") // prefix for api methods
public class MovieV1RestController {

@ResponseStatus(value=HttpStatus.NOT_FOUND)
@ExceptionHandler(MovieNotFoundException.class)
public String handleNotFoundMovie(Exception ex) {
return "LOCAL-class handler: " + ex.getMessage();
}

@Autowired
private MovieDAO movieDAO;

Expand All @@ -35,8 +42,7 @@ public List<Movie> getMovies() {
@ResponseBody // is redundant: @RestController adds it automatically
@GetMapping("/movies/{id}") // shortcut for @RequestMapping
public Movie getMovie(@PathVariable("id") Long id) {
Movie movie = checkIfMovieExist(id);
return movie;
return movieDAO.get(id).get();
}

// Example of use generic ResponseEntity instead of @ResponseStatus and @ResponseBody
Expand All @@ -49,18 +55,12 @@ public ResponseEntity createMovie(@RequestBody Movie movie) {
@DeleteMapping("/movies/{id}")
@ResponseStatus(value = HttpStatus.NO_CONTENT)
public void deleteMovie(@PathVariable Long id) {
checkIfMovieExist(id);
movieDAO.delete(id);
}

@PutMapping("/movies/{id}")
public Movie updateMovie(@PathVariable Long id, @RequestBody Movie movie) {
checkIfMovieExist(id);
return movieDAO.update(id, movie);
}

private Movie checkIfMovieExist(Long id) {
return movieDAO.get(id).orElseThrow(() -> new MovieNotFoundException(id));
}

}
14 changes: 3 additions & 11 deletions src/main/java/net/jwierzbo/rest/api/MovieV2SwaggerController.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import net.jwierzbo.rest.dao.MovieDAO;
import net.jwierzbo.rest.exception.MovieNotFoundException;
import net.jwierzbo.rest.model.Movie;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
Expand All @@ -26,7 +25,8 @@

/* This is example Controller class with extends description for SwaggerApi
* These @Api*** annotations are not necessary if we use @ResponseStatus
* and return Model objects instead of generic response */
* and return Model objects instead of generic response
*/

@Api(value="MovieController", description="List of favourite Movies")
@RestController
Expand All @@ -46,8 +46,7 @@ public List<Movie> getMovies() {
@ApiResponses(value = {@ApiResponse(code = 404, message = "Not Found")})
@GetMapping("/movies/{id}")
public Movie getMovie(@PathVariable("id") Long id) {
Movie movie = checkIfMovieExist(id);
return movie;
return movieDAO.get(id).get();
}

@ApiOperation(value = "Add new Movie",response = Movie.class)
Expand All @@ -70,7 +69,6 @@ public Movie createMovie(@RequestBody Movie movie) {
@DeleteMapping("/movies/{id}")
@ResponseStatus(value = HttpStatus.NO_CONTENT)
public void deleteMovie(@ApiParam(value = "Movie ID", required = true) @PathVariable Long id) {
checkIfMovieExist(id);
movieDAO.delete(id);
}

Expand All @@ -79,12 +77,6 @@ public void deleteMovie(@ApiParam(value = "Movie ID", required = true) @PathVari
@ApiResponse(code = 404, message = "Not Found")})
@PutMapping("/movies/{id}")
public Movie updateMovie(@PathVariable Long id, @RequestBody Movie movie) {
checkIfMovieExist(id);
return movieDAO.update(id, movie);
}

private Movie checkIfMovieExist(Long id) {
return movieDAO.get(id).orElseThrow(() -> new MovieNotFoundException(id));
}

}
5 changes: 3 additions & 2 deletions src/main/java/net/jwierzbo/rest/config/SwaggerConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
Expand All @@ -25,8 +26,8 @@ public Docket api() {
.apiInfo(apiInfo())
.globalResponseMessage(RequestMethod.GET,
Arrays.asList(new ResponseMessageBuilder()
.code(500)
.message("Server Error")
.code(HttpStatus.INTERNAL_SERVER_ERROR.value())
.message(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase())
.build()))
.select()
.apis(RequestHandlerSelectors.basePackage("net.jwierzbo.rest"))
Expand Down
11 changes: 5 additions & 6 deletions src/main/java/net/jwierzbo/rest/dao/MovieDAO.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import java.util.Optional;
import java.util.concurrent.atomic.AtomicLong;

import net.jwierzbo.rest.exception.MovieNotFoundException;
import net.jwierzbo.rest.model.Movie;
import org.springframework.stereotype.Component;

Expand All @@ -31,13 +32,13 @@ public List<Movie> list() {
}

public Optional<Movie> get(Long id) {

for (Movie c : movies) {
if (c.getId().equals(id)) {
return Optional.of(c);
}
}
return Optional.empty();

throw new MovieNotFoundException(id);
}

public Movie create(Movie movie) {
Expand All @@ -47,19 +48,17 @@ public Movie create(Movie movie) {
}

public Long delete(Long id) {

for (Movie c : movies) {
if (c.getId().equals(id)) {
movies.remove(c);
return id;
}
}

return null;
throw new MovieNotFoundException(id);
}

public Movie update(Long id, Movie movie) {

for (Movie c : movies) {
if (c.getId().equals(id)) {
movie.setId(c.getId());
Expand All @@ -69,7 +68,7 @@ public Movie update(Long id, Movie movie) {
}
}

return null;
throw new MovieNotFoundException(id);
}

}
Original file line number Diff line number Diff line change
@@ -1,13 +1,8 @@
package net.jwierzbo.rest.exception;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;


@ResponseStatus(HttpStatus.NOT_FOUND)
public class MovieNotFoundException extends RuntimeException {

public MovieNotFoundException(Long id) {
super("could not find movie with id: '" + id + "'.");
super("could not find movie with id: " + id);
}
}

0 comments on commit cf57393

Please sign in to comment.