When we call a rest service with bad end points then it will throw an exception what will show lots of ugly information from the server . So we can modify the exception information by developing our own custom exception.
lets see the practical example-
1. Creating our custom exception response pojo class that we want to sent back to the client.
public class StudentErrorResponse{
private int status;
private String message;
private long timestamp;
public StudentErrorResponse(int status,String message,long timeStamp){
this.status = status;
this.message = message;
this.timeStamp = timeStamp;
}
//Appropriate getter and setter for the properties
}
Now let's create our custom exception class.
public class StudentNotFound extends RuntimeException{
public StudentNotFound(String message,Throwable cause){
super(message,cause);
}
public StudentNotFound(String message){
super(message);
}
public StudentNotFound(String cause){
super(cause);
}
}
Now lets throws exception from our rest controller if student is not found,
@RestController
@RequestMapping("/api")
public class StudentRestController{
private List<Student> students ;
@PostConstruct //defining @PostConstruct will load data only once after class has been loaded .
public void loadData(){
students = new ArrayList<Student>();
students.add(new Student("lokman","hossain"));
students.add(new Student("sadia","muna"));
}
@GetMapping("/students")
public List<Student> getStudents(){
return students;
}
@GetMapping("/students/{studentId}")
public Student getStudent(@PathVariable int studentId){
if((studentId>students.size() )|| (studentId<0))
throw new StudentNotFound("Student not found with the given student id:"+studentId);
return students.get(studentId);
}
//Adding exception handler
@ExceptionHandler
public ResponseEntity<StudentErrorResponse> handleException(StudentNotFound exc){
StudentErrorResponse errorResponse = new StudentErrorResponse();
errorResponse.setStatus(HttpStatus.Not_found.value());
errorResponse.setMessage(exc.getMessage());
errorResponse.setTimeStamp(System.currentTimeMillis());
return new ResponseEntity<>(errorResponse, HttpStatus.NOT_FOUND);// will return a json .jackson will convert the pojo to json .
}
What if the user request using character in request parameter without giving integer value . then server again will show an ugly message .so we should handle it . so lets create another exception handler ..
@ExceptionHandler
public ResponseEntity<StudentErrorResponse> handleException(Exception ex){
StudentErrorResponse errorResponse = new StudentErrorResponse();
errorResponse.setStatus(HttpStatus.BAD_REQUEST.value());
errorResponse.setMessage(exc.getMessage());
errorResponse.setTimeStamp(System.currentTimeMillis());
return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
}
}
No comments:
Post a Comment