Gro*_*oth 8 error-handling spring spring-mvc spring-boot
我正在尝试在Spring-Boot中为我的控制器编写错误处理程序,以便捕获大多数可能的错误(Spring,sql等).到目前为止,我能够通过Null获得JSON响应,但是我无法将任何数据放入其中.当我尝试收到错误消息时,我只收到一个空白页面.
import java.io.IOException;
import java.sql.SQLException;
import javax.servlet.http.HttpServletRequest;
import org.springframework.boot.autoconfigure.web.ErrorController;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.multiaction.NoSuchRequestHandlingMethodException;
@RestController
public class BasicErrorController implements ErrorController {
    private static final String ERROR_PATH = "/error";
    @RequestMapping(value=ERROR_PATH)
    @ExceptionHandler(value = {NoSuchRequestHandlingMethodException.class, SQLException.class, IOException.class, RuntimeException.class, Exception.class})
    public ErrorBody defaultErrorHandler(HttpServletRequest request, Exception e) {     
        ErrorBody eBody = new ErrorBody();         
        eBody.setMessage(e.getCause().getMessage());
        return eBody;
    }
}
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class ErrorBody {
    private String dateTime;
    private String exception;
    private String url;
    private String message;
}
小智 6
哟可以这样做:
 @ControllerAdvice
   public class ControllerExceptionTranslator {
    @ExceptionHandler(EntityNotFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    @ResponseBody
    SimpleErrorMessage handleException(EntityNotFoundException exception){
        log.debug("Entity Not Found Exception {}",exception.getMessage());
        log.trace(exception.getMessage(),exception);
        return new SimpleErrorMessage("Entity not found","This resource was not found");
    }
    @ExceptionHandler({UsernameNotFoundException.class})
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ResponseBody
    SimpleErrorMessage handleException(UsernameNotFoundException exception){
        log.debug("Username not found {}",exception.getLocalizedMessage());
        log.trace(exception.getMessage(),exception);
        return new SimpleErrorMessage("Unaouthorized"," ");
    }
}
| 归档时间: | 
 | 
| 查看次数: | 15957 次 | 
| 最近记录: |