11package com .example .myquizapp .controller ;
22
3+ import java .util .ArrayList ;
34import java .util .List ;
45
56import org .springframework .beans .factory .annotation .Autowired ;
7+ import org .springframework .http .HttpStatus ;
8+ import org .springframework .http .ResponseEntity ;
69import org .springframework .web .bind .annotation .DeleteMapping ;
710import org .springframework .web .bind .annotation .GetMapping ;
811import org .springframework .web .bind .annotation .PathVariable ;
@@ -26,23 +29,29 @@ public class QuestionController {
2629
2730 // url => http://localhost:8080/question/allQuestions
2831 @ GetMapping ("allQuestions" )
29- public List <Question > getAllQuestion () {
30-
31- // return "Hi, these are your all questions2";
32- return questionService .getAllQuestions ();
32+ public ResponseEntity <List <Question >> getAllQuestion () {
33+ // either we can do exception handling in controller or in service, as per your wish!
34+ // return "Hi, these are your all questions2";
35+ try {
36+ return new ResponseEntity <>(questionService .getAllQuestions (), HttpStatus .OK );
37+ }catch (Exception e ) {
38+ e .printStackTrace ();
39+ return new ResponseEntity <>(new ArrayList <>(), HttpStatus .BAD_REQUEST );
40+ }
3341 }
3442
3543 @ GetMapping ("category/{category}" )
36- public List <Question > getQuestionsByCategory (@ PathVariable String category ){
44+ public ResponseEntity < List <Question > > getQuestionsByCategory (@ PathVariable String category ){
3745 // if multiple pathvariables, eg. category/{mycategory}/{mydifficulty} then -
3846 // public List<Question> getQuestionsByCategory(@PathVariable("mycategory") String category, @PathVariable("mydifficulty") String difficulty){
47+
48+ // in this example, exception handling is done in service instead of inside controller
3949 return questionService .getQuestionsByCategory (category );
4050 }
4151
4252 @ PostMapping ("add" )
43- public String addQuestion (@ RequestBody Question question ) { // accepting JSON from client
44- questionService .addQuestion (question );
45- return "successss!!!" ;
53+ public ResponseEntity <String > addQuestion (@ RequestBody Question question ) { // accepting JSON from client
54+ return questionService .addQuestion (question );
4655 }
4756
4857 @ DeleteMapping ("delete/{qid}" )
0 commit comments