Blog Detail

  • Home
  • Exception Handling in RESTful web services

Exception Handling in RESTful web services

In this blog I posted the how can we throw the exception to the client in JSON format.

Create the custom exception

package com.samplecoder.emo.exceptions;

public class StudentNotFoundException extends RuntimeException{
	public StudentNotFoundException(String message) {
		super(message);
	}
}

Create Controller Advicer

package com.samplecoder.emo.handler;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.WebRequest;

import com.samplecoder.emo.exceptions.StudentNotFoundException;

@RestControllerAdvice
public class StudentExceptionsHandlers {

	@ExceptionHandler({StudentNotFoundException.class})
	public ResponseEntity<String> studentNotFound(RuntimeException ex, WebRequest request){
		return new ResponseEntity<String>(ex.getMessage(), HttpStatus.NOT_FOUND);
	}
}

Now just throw Student Not Found Exception from where ever you want the exception. In this sample code I have throwing the exception in Student controller

package com.samplecoder.emo.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.samplecoder.emo.entity.Student;
import com.samplecoder.emo.exceptions.StudentNotFoundException;
import com.samplecoder.emo.repository.StudentRepository;

@RestController
@RequestMapping("/api/student")
public class StudentController {
	
	@Autowired
	private StudentRepository studentRepository;
	

	@GetMapping("/get/{id}")
	private Student get(@PathVariable(name = "id", required = true) Integer id) {
		Student student = studentRepository.findById(id).orElse(null);
		if(student == null)
			throw new StudentNotFoundException("Student not found");
		return student;
	}
	
}

Postman response

Request: http://localhost:8080/api/student/get/10
Response: Student not found

Write a comment