在SpringBoot中引发异常

时间:2019-10-08 16:46:46

标签: java spring api spring-boot exception

因此,我正在尝试为GET请求引发异常(即将出现更多请求,但现在我正在处理GET)。在创建错误包及其中的类之前,我遇到了常见的Java空指针错误。但是,在创建它们之后,我只得到了这个

{}

当我输入错误的ID时,在邮递员

中。这是我的从异常包到控制器的类

RecordNotFoundException类

package com.yash.questionnaire.exception;

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

@ResponseStatus(HttpStatus.NOT_FOUND)
public class RecordNotFoundException extends RuntimeException
{
    public RecordNotFoundException(String exception) {
        super(exception);
    }
}

ErrorResponse类

package com.yash.questionnaire.exception;

import java.util.List;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "error")
public class ErrorResponse
{
    public ErrorResponse(String message, List<String> details) {
        super();
        this.message = message;
        this.details = details;
    }

    //General error message about nature of error
    private String message;

    //Specific errors in API request processing
    private List<String> details;

    //Getter and setters
}

CustomExceptionHandler类

package com.yash.questionnaire.exception;

import java.util.ArrayList;
import java.util.List;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

@SuppressWarnings({"unchecked","rawtypes"})
@ControllerAdvice
public class CustomExceptionHandler extends ResponseEntityExceptionHandler
{
    @ExceptionHandler(Exception.class)
    public final ResponseEntity<Object> handleAllExceptions(Exception ex, WebRequest request) {
        List<String> details = new ArrayList<>();
        details.add(ex.getLocalizedMessage());
        ErrorResponse error = new ErrorResponse("Server Error", details);
        return new ResponseEntity(error, HttpStatus.INTERNAL_SERVER_ERROR);
    }

    @ExceptionHandler(RecordNotFoundException.class)
    public final ResponseEntity<Object> handleUserNotFoundException(RecordNotFoundException ex, WebRequest request) {
        List<String> details = new ArrayList<>();
        details.add(ex.getLocalizedMessage());
        ErrorResponse error = new ErrorResponse("Record Not Found", details);
        return new ResponseEntity(error, HttpStatus.NOT_FOUND);
    }

    @Override
    protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
        List<String> details = new ArrayList<>();
        for(ObjectError error : ex.getBindingResult().getAllErrors()) {
            details.add(error.getDefaultMessage());
        }
        ErrorResponse error = new ErrorResponse("Validation Failed", details);
        return new ResponseEntity(error, HttpStatus.BAD_REQUEST);
    }
}

StudyController类


package com.yash.questionnaire.web;

import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.CrossOrigin;
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.PutMapping;
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.yash.questionnaire.exception.RecordNotFoundException;
import com.yash.questionnaire.model.Study;
import com.yash.questionnaire.repository.MapValidationError;
import com.yash.questionnaire.repository.StudyRepository;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@RestController
@RequestMapping("/api")
@CrossOrigin(origins = "*")
@Api(value= "DDR", description="This API provides the facility to create a new Study")
public class StudyController {

    @Autowired
    private StudyRepository repository;

    @Autowired
    private MapValidationError mapValidationError;    //ToDo: to fetch Json post request

    @ApiOperation(value = "Read a study by study-name")
    @GetMapping("/studies/{studyType}")
    public ResponseEntity<Map<String, Object>> getByStudyType(@ApiParam(value = "Questionnaire StudyType will retrieve", required = true) @PathVariable("studyType") String studyType) {
        try {
            return new ResponseEntity<>(repository.getByStudyType(studyType), HttpStatus.OK);

        } catch (RecordNotFoundException ex) {
            throw new RecordNotFoundException("Invalid studyType : " + studyType);
        }
    }

}

有人可以帮我弄清楚如何显示我放在StudyController类中的自定义错误,而不只是{}

1 个答案:

答案 0 :(得分:0)

也许您应该删除异常类上的@ResponseStatus(HttpStatus.NOT_FOUND)。